分享技术 · 探索极限 · Code is Art
开发工具 发布 2022-07-08 708 阅读 约 2 分钟阅读

Python 3.10 新特性:上下文管理器、match case 与类型提示

整理 Python 3.10 中几个实用新特性,包括多上下文管理器、match case 结构和 X | Y 联合类型提示。

1. 上下文管理器

with 语句支持一次打开多个上下文管理器:

# Python 3.9
with open("test1.txt") as f1:
    with open("test2.txt") as f2:
        pass

# Python 3.10
with (
    open("test1.txt") as f1,
    open("test2.txt") as f2,
):
    pass

2. 新增 match case 语句

新增类似其它语言中 switch case 的结构:

status = 404

match status:
    case 400:
        res = "Bad request"
    case 404:
        res = "Not found"
    case 500 | 501 | 502 | 503 | 504:
        res = "Server error"
    case ("error", code, _):
        res = f"An error {code} occurred"
    case _:
        res = "Something's wrong with the internet"

3. 新的类型提示联合运算符

Python 3.10 引入了 X | Y 语法的类型提示联合运算符。

# Python 3.9
def add(x: Union[int, float], y: Union[int, float]) -> Union[int, float]:
    return x + y

# Python 3.10
def add(x: int | float, y: int | float) -> int | float:
    return x + y

这个新语法也可以用在 isinstance()issubclass() 中。

isinstance(5, int | str | float)

发表回复