來源:juejin.cn/post/7015590447745613854
Python 3.10正式發布,你嘗鮮了嗎?
本文參考自 Python官方文檔 :Python Release Python 3.10.0 | Python.org[1]
在正值國慶假期人山人海的2021年10月4號,Python官方正式發布了Python3.10.0[2]。作為一隻假期期間宅著不動的coding人,自然是第一時間體驗了一波。相較於之前的版本,該版本有以下主要變更。
新的 Union Type表達新版本簡化了 Union Type 的使用 ,改為更為簡潔的|
舊版:
from typing import Union
a: Union[int, str] = 1新的版本:
a: str | int = 1二者完全等價:
Union[int, str] == int | str # True這類變化在其他地方也相似:
# 舊版:
# def f(list: List[Union[int, str]], param: Optional[int]) -> Union[float, str]
def f(list: List[int | str], param: int | None) -> float | str:
pass
f([1, "abc"], None)
# 舊版:
# typing.List[typing.Union[str, int]]
typing.List[str | int]
list[str | int]
# 舊版:
# typing.Dict[str, typing.Union[int, float]]
typing.Dict[str, int | float]
dict[str, int | float]該特性也可用於 isinstance和issubclass
# True
isinstance("FunnySaltyFish", int|str)
# True
issubclass(str, str|int)
zip 可選嚴格模式zip新增可選參數strict, 當該選項為True時,傳入zip的兩個可迭代項長度必須相等,否則將拋出 ValueError
舊版(及不加此參數),當二者長度不等時,以長度較小的為準
names = ["a","b","c","d"]
numbers = [1,2,3]
z = zip(names,numbers)
for each in z:
print(each)
# ('a', 1)
# ('b', 2)
# ('c', 3)設置strict為True
# ...
z = zip(names,numbers,strict=True)
# ...
d:\projects\python\learn\Py310探索.py in <module>
3 numbers = [1,2,3]
4 z = zip(names,numbers,strict=True)
----> 5 for each in z:
6 print(each)
ValueError: zip() argument 2 is shorter than argument 1
帶括號的上下文管理器with可以加括號了
with (CtxManager() as example):
...
with (
CtxManager1(),
CtxManager2()
):
...
with (CtxManager1() as example,
CtxManager2()):
...
with (CtxManager1(),
CtxManager2() as example):
...
with (
CtxManager1() as example1,
CtxManager2() as example2
):
...如
import pathlib
p = pathlib.Path()
p1 = p/"text1.txt" # 內容:文本1的內容
p2 = p/"text2.txt" # 內容:文本2的內容
with(
p1.open(encoding="utf-8") as f1,
p2.open(encoding="utf-8") as f2
):
print(f1.read(), f2.read(), sep="\n")
# 文本1的內容
# 文本2的內容
顯式類型別名使用 TypeAlias 顯式標註類型別名,提高可讀性
舊的方式:
x = int
def plus_int(a:x,b:x) -> x:
return a+b可以看到,x很容易被搞混
新的方式:使用 TypeAlias表明這是個別名
from typing import TypeAlias
x : TypeAlias = int
def plus_int(a:x,b:x) -> x:
return a+b
match...case語句對,就是其他語言的switch-case,python終於提供了支持,還是加強版的
完整語法參見:PEP 634 -- Structural Pattern Matching: Specification | Python.org[3]
舉幾個例子:
基本的類型匹配:
day = 6
match day:
case 1:
print("星期一")
case 6 | 7:
print("周末")
case _ :
print("其他情況")subject:這在處理命令行參數的時候特別有用
"""
@copyright : [FunnySaltyFish](https://funnysaltyfish.github.io)
@date : 2021/10/05 21:08:42
"""
command = "save 1.txt"
# 試著把command改成 list / copy 1.txt 2.txt 看看效果
match command.split(" "):
case ["list"]:
print("列出文件~")
case ["save", file_name]:
print(f"保存文件到 {file_name}")
case ["copy",source,target]:
print(f"拷貝 {source} -> {target}")也可以匹配對象:
class Person():
pass
class Student(Person):
def __init__(self, id: int) -> None:
self.id = id
class Teacher(Person):
def __init__(self, name: str) -> None:
self.name = name
a = Student(1)
# a = Student(2)
# a = Teacher("FunnySaltyFish")
match a:
case Student(id = 2):
print(f"這是位學生,且id正好是2")
case Student():
print(f"這是學生,id為{a.id}")
case Teacher():
print(f"這是老師, 姓名為{a.name}")當然也可以匹配字典:
d = {
"name" : "李四", # 張三
"age" : 18,
"hobby" : "閱讀"
}
match d:
case {"name":"張三", **args}:
# **收集其他參數
print("這是張三", args) # 這是張三 {'age': 18, 'hobby': '閱讀'}
case {"name" : name , "age" : age, "hobby": hobby}:
print(f"我叫{name}, 今年{age}歲, 喜歡{hobby}") #我叫李四,今年18歲,喜歡閱讀更複雜的還有結合Guard、匹配捕獲等使用,具體可以參見:PEP 635 -- Structural Pattern Matching: Motivation and Rationale | Python.org[4] 和 PEP 636 -- Structural Pattern Matching: Tutorial | Python.org[5]
更友好的報錯提示現在,當你的括號、引號未閉合時,python會拋出更加清晰明了的錯誤
str = "未閉合的str
File "d:\projects\python\learn\Py310探索.py", line 90
str = "未閉合的str
^
SyntaxError: unterminated string literal (detected at line 90)arr = [1, 2, 2, 3
File "d:\projects\python\learn\Py310探索.py", line 91
arr = [1, 2, 2, 3
^
SyntaxError: '[' was never closed
其他一些更新:distutils 被棄用推薦使用 setuptools
需要 OpenSSL 1.1.1 及以上版本移除 Py_UNICODE編碼APIPyUnicodeObject的wstr被棄用,並將在之後移除完。摸魚去了。
參考資料[1]https://www.python.org/downloads/release/python-3100/: https://link.juejin.cn?target=https%3A%2F%2Fwww.python.org%2Fdownloads%2Frelease%2Fpython-3100%2F
[2]https://www.python.org/downloads/release/python-3100/: https://link.juejin.cn?target=https%3A%2F%2Fwww.python.org%2Fdownloads%2Frelease%2Fpython-3100%2F
[3]https://www.python.org/dev/peps/pep-0634/#id25: https://link.juejin.cn?target=https%3A%2F%2Fwww.python.org%2Fdev%2Fpeps%2Fpep-0634%2F%23id25
[4]https://www.python.org/dev/peps/pep-0635/#id15: https://link.juejin.cn?target=https%3A%2F%2Fwww.python.org%2Fdev%2Fpeps%2Fpep-0635%2F%23id15
[5]https://www.python.org/dev/peps/pep-0636/: https://link.juejin.cn?target=https%3A%2F%2Fwww.python.org%2Fdev%2Fpeps%2Fpep-0636%2F