Python 3.10 有哪些最新特性 ?

Python 3.10 的開發(fā)已經(jīng)穩(wěn)定下來,我們終于可以測試最終版本中將包含的所有新功能。
下面我們將介紹 Python 3.10 中最有趣的一些新增功能——結(jié)構(gòu)模式匹配、帶括號的上下文管理器、 更多類型以及新的報錯消息。
結(jié)構(gòu)模式匹配
結(jié)構(gòu)模式匹配是要添加到 Python 中的一個很棒的功能。想象一個如下所示的 if-else 語句(Python 3.9):
http_code = "418"
if http_code == "200":
print("OK")
elif http_code == "404":
print("Not Found")
elif http_code == "418":
print("I'm a teapot")
else:
print("Code not found")
I'm a teapot
http_code = "418"
match http_code:
case"200":
print("OK")
case"404":
print("Not Found")
case"418":
print("I'm a teapot")
case _:
print("Code not found")
match-case語句——很酷,但目前還沒有什么特別之處。使 match-case語句如此有趣的原因是一種稱為結(jié)構(gòu)模式匹配的東西。結(jié)構(gòu)模式匹配允許我們執(zhí)行相同的 match-case 邏輯,但基于我們的比較對象的結(jié)構(gòu)是否與給定的模式匹配。
dict_a = {
'id': 1,
'meta': {
'source': 'abc',
'location': 'west'
}
}
dict_b = {
'id': 2,
'source': 'def',
'location': 'west'
}
dict_a,如下所示:
{
'id': int,
'meta': {'source': str,
'location': str}
}
dict_b的模式:
{
'id': int,
'source': str,
'location': str
}
match-case語句中,以及有效的 else/和包羅萬象的 case_ - 我們得到:
# loop through both dictionaries and a 'test'
for d in[dict_a, dict_b, 'test']:
match d:
case{'id': ident,
'meta': {'source': source,
'location': loc}}:
print(ident, source, loc)
case{'id': ident,
'source': source,
'location': loc}:
print(ident, source, loc)
case _:
print('no match')
1 abc west
2def west
no match
with open('file1.txt', 'r') as fin, open('file2.txt', 'w') as fout:
fout.write(fin.read())
\ 行繼續(xù)符:
with open('file1.txt', 'r') as fin, \
open('file2.txt', 'w') as fout:
fout.write(fin.read())
with(open('file1.txt', 'r') as fin,
open('file2.txt', 'w') as fout):
fout.write(fin.read())
with(open('file1.txt', 'r') as fin,
open('file2.txt', 'w') as fout):
fout.write(fin.read())
Typing功能OR 邏輯,我們之前使用 Union 方法來實現(xiàn):
from typing importUnion
def add(x: Union[int, float], y: Union[int, float]):
return x + y
fromtypingimportUnion,并且 Union[int,float] 已經(jīng)簡化為 int|float,看起來更簡潔:
def add(x: int| float, y: int| float):
return x + y
SyntaxError: unexpected EOF while parsing







from collections import namedtoplo
> AttributeError: module'collections' has no attribute 'namedtoplo'. Did you mean: namedtuple?
AttributeError 與之前相同,但增加了一個建議的屬性名稱—— namedtoplo 被標識為屬性 namedtuple的潛在拼寫錯誤。NameError消息也有相同的改進:
new_var = 5
print(new_vr)
> NameError: name 'new_vr'isnotdefined. Did you mean: new_var?
https://www.python.org/downloads/release/python-3100b1/

還不過癮?試試它們
▲提升 Python 性能 - Numba 與 Cython
