Python 3.10都出了?这些新语法你还不会用?
各位追新党们好啊。
今天来聊聊Python 3.10的新语法。
每次Python出新版本,你是不是都是"哦,又更新了",然后继续用老语法。
别这样。今天混子哥带你看看3.10那些实用的新特性,保证让你大呼"真香"。
结构化匹配,match-case才是switch的亲爹
Python开发者等了20年的switch终于来了,只不过换了个名字叫match。
# 老版本 - if-elif-else 地狱
defget_http_status(status):
if status == 200:
return"OK"
elif status == 404:
return"Not Found"
elif status == 500:
return"Server Error"
elif status == 301:
return"Redirect"
else:
return"Unknown"
# Python 3.10+ - match-case 优雅多了
defget_http_status(status):
match status:
case 200:
return"OK"
case 404:
return"Not Found"
case 500:
return"Server Error"
case 301 | 302 | 307:
return"Redirect"
case _:
return"Unknown"
# 高级用法 - 带条件的匹配
defdescribe_point(point):
match point:
case (0, 0):
return"原点"
case (x, 0) if x > 0:
returnf"正x轴上的点({x})"
case (x, y) if x == y:
returnf"对角线上的点"
case [x, y, z]:
returnf"3D点: {x}, {y}, {z}"
case _:
return"其他点"
print(describe_point((1, 0)))
print(describe_point([1, 2, 3]))
精确的错误信息,调试效率翻倍
# Python 3.10之前 - 错误信息让人摸不着头脑
>>> a = {"a": 1}
>>> a["b"]
KeyError: 'b'
# Python 3.10+ - 错误信息详细多了
>>> a = {"a": 1}
>>> a["b"]
KeyError: 'b'
>>> a = 1
>>> a.append(2)
AttributeError: 'int' object has no attribute 'append'. Did you mean 'integer'?
括号跨行更优雅,现在可以这样写
# Python 3.9之前 - 括号里的字符串必须同行
query = ("SELECT * FROM users "
"WHERE id = 1 "
"ORDER BY created_at DESC")
# Python 3.9+ - 括号里的字符串可以跨行
query = (
"SELECT * FROM users "
"WHERE id = 1 "
"ORDER BY created_at DESC"
)
# Python 3.10+ - 更进一步,支持圆括号上下文管理器
with (
open('file1.txt') as f1,
open('file2.txt') as f2,
):
content = f1.read() + f2.read()
类型提示大升级,TypeAlias让人眼前一亮
from typing import TypeAlias, Union
# Python 3.9之前 - 类型定义乱七八糟
defprocess(data):
pass
# Python 3.10+ - TypeAlias 让类型定义更清晰
Vector: TypeAlias = list[float]
Matrix: TypeAlias = list[list[float]]
defscale(vector: Vector, factor: float) -> Vector:
return [x * factor for x in vector]
# 3.10+ 还能用 | 表示联合类型
IntOrStr: TypeAlias = int | str
零依赖Batteries,str去除、bytes格式化全都有
# Python 3.9+ - 字符串操作新增一堆方法
" hello ".removeprefix(" ")
" hello ".removesuffix(" ")
"hello world".remove("o")
# 字典合并操作符
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
# Python 3.9+ - 字典合并更新操作符
merged = d1 | d2
d1 |= d2
# bytes格式化,终于不用那么别扭了
name = b"World"
f"Hello, {name}!".encode()
错误回溯信息更精确了
# Python 3.10之前
>>> eval("1 + * 2")
File "<stdin>", line 1
eval("1 + * 2")
^^^^^
SyntaxError: invalid syntax
# Python 3.11+ - 更精确的错误位置
>>> eval("1 + * 2")
File "<string>", line 1
1 + * 2
~~^~
SyntaxError: invalid syntax
参数检查更严格了
# Python 3.10之前 - zip只返回一个
list(zip([1,2,3], [4,5]))
# Python 3.10+ - strict参数
list(zip([1,2,3], [4,5], strict=True))
性能提升才是重头戏
Python 3.11比3.8快了多少?官方数据:
import timeit
code = """
result = sum(range(1000000))
"""
t1 = timeit.timeit(code, number=100, globals=globals())
print(f"耗时: {t1:.4f}秒")