python3.10发行已经有一段时间了,但是时至今日才开始用上python3.10版本,说实话有点惭愧。下面来记录一下,在Python3.10版本中几个亮眼的语法变更:
在以前,我们如果需要打开多个文件,我们通常会使用多个with
操作,就像这样:
with open("a.txt", "r") as fa:
pass
with open("b.txt", "w") as fb:
pass
在python3.10中,引入了带括号的上下文管理器,我们可以这样写了:
with (
open("a.txt", "r") as fa,
open("b.txt", "w") as fb
):
pass
结构模式匹配已以match
语句 和具有关联操作的模式的case
语句的形式添加。模式由序列、映射、原始数据类型以及类实例组成。模式匹配使程序能够从复杂的数据类型中提取信息,在数据结构上进行分支,并根据不同形式的数据应用特定的操作。如下:
match subject:
case <pattern_1>:
<action_1>
case <pattern_2>:
<action_2>
case <pattern_3>:
<action_3>
case _:
<action_wildcard>
你还可以使用|
将多个条件组合在一个模式中:
case 401 | 403 | 404:
return "Not Allowed"
如果未使用case _
匹配,并且上面的case
条件都不满足的情况下,将会发生空操作,即返回一个None
用于match
匹配的变量,除了数字或字符串之外,还可以是一个元组或者列表,甚至是一个类的对象。使用如下:
def location(points):
match points:
case (0, 1):
print("(0, 1) is the point's location.")
case (1, 0):
print("(1, 0) is the point's location.")
case _:
print("other")
if __name__ == "__main__":
location((0, 1)) # (0, 1) is the point's location.
location((1, 0)) # (1, 0) is the point's location.
location((1, 1)) # other
def match_case(var):
match var:
case []:
print("var is empty")
case [1, 2]:
print("var is [1, 2]")
case [1, 1]:
print("var is [1, 1]")
case _:
print("other")
if __name__ == "__main__":
match_case([]) # var is empty
match_case([1, 2]) # var is [1, 2]
match_case([1, 1]) # var is [1, 1]
match_case([2, 2]) # other
class Point(object):
x: int
y: int
def location(point):
match point:
case Point(x=0, y=0):
print("Origin is the point's location")
case Point(x=0, y=y): # x为0,y为任一值
print(f"Y={y} and the point is on the y-axis")
case Point(x=x, y=0): # y为0,x为任一值
print(f"X={x} and the point is on the x-axis")
case Point(): # x或y没有值,或都没有值的情况
print("The point is located somewhere else on the plane.")
case _:
print('not a plane')
match test_variable:
case ('warning', code, 40):
print("A warning has been received.")
case ('error', code, _):
print(f"An error {code} occurred.")
在上述情况下,test_variable将匹配 (‘error’, code, 100) 和 (‘error’, code, 800)。
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.")
结构模式匹配的使用跟Java的switch...case
语法有点类似!
在之前我们需要对一个参数对多类型的匹配时,我们需要使用到Union
如下:
from typing import Union
def square(number: Union[int, float]):
return number ** 2
表示,可以接收int
或者float
类型的参数,在Python3.10中,我们可以使用|
操作符号来简化该操作,如下:
def square(number: int|float):
return number ** 2
这个新语法也可以作为instance()
和issublcass()
的第二个参数:
>>> isinstance(1, int | str)
True
更多语法变更: