Posted onInCodingDisqus: Word count in article: 1.9kReading time ≈2 mins.
Python3.10的新特性!
新版本的Python 3.10主要有三个大变化:
增加模式匹配
更好的错误提示
更好的类型检查
结构化模式匹配
模式匹配主要通过mathc和case关键字,具有如下实现方法:
1 2 3 4 5 6 7 8 9
match subject: case <pattern_1>: <action_1> case <pattern_2>: <action_2> case <pattern_3>: <action_3> case _: <action_wildcard>
模式匹配大大增加了控制流的清晰度和表达能力:
比如:
1 2 3 4 5 6 7 8 9 10
command = input() match command.split(): case ["quit"]: quit() case ["load", filename]: load_from(filename) case ["save", filename]: save_to(filename) case _: print (f"Command '{command}' not understood")
也可以匹配类型:
1 2 3
match media_object: case Image(type=media_type): print (f"Image of type {media_type}")
还可以配合守卫使用:
1 2 3 4 5
match point: case Point(x, y) if x == y: print(f"The point is located on the diagonal Y=X at {x}.") case Point(x, y): print(f"Point is not on the diagonal.")
File ".\test.py", line 1 print ("Hello" ^ SyntaxError: '(' was never closed
在比如:
1 2 3 4 5
{x,y for x,y in range(100)} File "<stdin>", line 1 {x,y for x,y in range(100)} ^ SyntaxError: did you forget parentheses around the comprehension target?
更好的类型检查支持
增加了ParamSpec和TypeVar,可以让函数的类型检查再有装饰器的情况下正常工作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
from typing import Awaitable, Callable, ParamSpec, TypeVar