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,
):
pass2. 新增 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)