Python 3.10 新特性介绍
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.新的类型提示联合运算符
新引入了“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)