Python 更新记录
Python 发布策略
Python的版本采用年度更新策略,每年十月发布新版本,如3.10版本在2020年10月5日发布,3.11版本在2021年10月4日发布。 本文旨在记录各重大特性的变更记录,方便使用新特性时参考版本。
python 3.9 2020年10月5日
- 字典合并(PEP 584)
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
merged = d1 | d2 # {'a': 1, 'b': 3, 'c': 4}
d1 |= d2 # d1 = {'a': 1, 'b': 3, 'c': 4}
str.removeprefix()
和str.removesuffix()
(PEP 616)
s = "hello world"
s.removeprefix("hello") # " world"
s.removesuffix("world") # "hello "
- 集合泛型(PEP 585)
# old
import typing.List
def func(s: typing.List[int]):
pass
# new
def func(s: list[int]):
pass
再也不需要导入typing.List了,直接使用list[int]即可。
PEG解析器(PEP 617) 语法上无影响,主要影响解析器的实现,为后续的一些语法提供支撑。
zoneinfo(PEP 615) 和graphlib
import zoneinfo
tz = zoneinfo.ZoneInfo("Asia/Shanghai")
方便了对时区(包括夏令时)的处理。
graphlib主要增加了TopologicalSorter
,用于拓扑排序。
- 性能优化 Vectorcall 协议(PEP 590)使用范围扩大,范围扩大到
range
、tuple
、set
、frozenset
、list
、dict
的调用。
优化了多线程信号处理机制。
提高短ASCII字符串的性能。
python 3.10 2021年10月4日
- 结构化模式匹配 (PEP 634, 635, 636): 引入
match
和case
语句,用于模式匹配。
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
case 401 | 403 | 404:
return "Not allowed"
- 括号上下文
with (
open("file1.txt") as f1,
open("file2.txt") as f2
):
# do with f1, f2
- 使用"|"定义联合类型而不是typing.Union(PEP 604)
# old
def func(x: typing.Union[int, str]):
pass
# new
def func(x: int | str):
pass
- C API int 类型新增了 int.bit_count() 方法。
zip() 函数新增了一个 strict 标志 (PEP 618),用于强制所有可迭代对象的长度相等。
新增了两个内置函数 aiter() 和 anext(),用于异步迭代。
@staticmethod 和 @classmethod 装饰器得到改进,现在可以继承方法属性并拥有一个新的 wrapped 属性。
新增了 inspect.get_annotations() 函数,用于安全地计算注解,包括对字符串化注解进行反字符串化。
ssl 模块现在要求 OpenSSL 1.1.1 或更新版本,并具有更安全的默认设置。
python 3.11 2022年10月24日
性能提升
- 与 3.10 相比平均提升 25%(部分场景提升 10-60%)
- 更快的启动速度:通过"冻结导入"实现
- 专门化自适应解释器:运行时识别热点代码,用更快的版本替换通用字节码
- 更廉价、惰性的 Python 帧
- 内联 Python 函数调用
异常处理增强
- 细粒度错误定位 (PEP 657)
# 现在错误信息会精确指向问题表达式
# 例如:TypeError: unsupported operand type(s) for +: 'int' and 'str'
# 错误位置会用 ~^~~ 标记
- 异常组 (PEP 654)
try:
raise ExceptionGroup("多个错误", [
ValueError("值错误"),
TypeError("类型错误")
])
except* ValueError:
print("处理值错误")
except* TypeError:
print("处理类型错误")
- 异常注解 (PEP 678)
try:
raise ValueError("原始错误")
except ValueError as e:
e.add_note("这是额外的上下文信息")
raise
- 类型系统增强
- 可变参数泛型 (PEP 646)
from typing import TypeVarTuple, TypeVar
Shape = TypeVarTuple('Shape')
T = TypeVar('T')
class Array(Generic[T, *Shape]):
pass
- TypedDict 增强 (PEP 655)
from typing import TypedDict, Required, NotRequired
class Movie(TypedDict):
title: Required[str]
year: Required[int]
rating: NotRequired[float]
- Self 类型 (PEP 673)
from typing import Self
class Shape:
def set_scale(self, scale: float) -> Self:
self.scale = scale
return self
- 标准库更新
- tomllib 模块 (PEP 680):用于解析 TOML 文件
- asyncio 新增 TaskGroup
- enum 模块增强:新增 StrEnum、ReprEnum 和 EnumType
- re 模块支持原子组和所有格量词
python 3.12 2023年10月2日
- 类型系统增强
- 类型参数语法 (PEP 695)
# 新的类型别名语法
type Point = tuple[float, float]
# 新的泛型类语法
class Vector[T]:
def __init__(self, x: T, y: T):
self.x = x
self.y = y
# 新的泛型函数语法
def first[T](items: list[T]) -> T:
return items[0]
- TypedDict 增强 (PEP 692)
from typing import TypedDict, Unpack
class Options(TypedDict):
timeout: int
retries: int
def process(**options: Unpack[Options]):
pass
- @typing.override 装饰器 (PEP 698)
from typing import override
class Parent:
def method(self) -> None:
pass
class Child(Parent):
@override
def method(self) -> None:
pass
- 语法增强
- f-string 语法规范化 (PEP 701)
# 支持多行表达式
f"""
{{
'name': 'Alice',
'age': 30
}}
"""
# 支持注释
f"Value: {value # 这是一个注释}"
# 支持任意嵌套
f"{f"{f"{value}"}"}"
- 推导式内联 (PEP 709)
# 性能提升的列表推导式
squares = [x * x for x in range(1000)]
- 并发与性能
- 每个解释器独立的 GIL (PEP 684)
- 低影响监控 API (PEP 669)
- 缓冲协议可访问性 (PEP 688)
from collections.abc import Buffer
class MyBuffer:
def __buffer__(self, flags: int) -> Buffer:
# 实现缓冲区协议
pass
- 标准库更新
- itertools.batched() 新增
from itertools import batched
# 将元素分组为大小为3的元组
for batch in batched(range(10), 3):
print(batch) # (0, 1, 2), (3, 4, 5), (6, 7, 8), (9,)
- pathlib.Path 增强
from pathlib import Path
class CustomPath(Path):
def custom_method(self):
pass
# 新增 walk() 方法
for root, dirs, files in Path(".").walk():
pass
- sqlite3 模块增强
import sqlite3
# 自动提交模式
conn = sqlite3.connect(":memory:", autocommit=True)
错误信息改进
- NameError 提供更智能的建议
- ImportError 提供更精确的导入建议
- 改进的语法错误提示
性能优化
- 推导式执行速度提升(最高2倍)
- re.sub() 和 re.subn() 性能提升(2-3倍)
- asyncio.Task 创建速度提升
- tokenize 模块性能提升(最高64%)
弃用与移除
- 计划在 3.13 中移除的模块:aifc、cgi、crypt 等
- lib2to3 和 2to3 程序被弃用
- 移除 asynchat 和 asyncore 模块
- 移除 distutils 包
python 3.13 2024年10月7日
- 交互式解释器 (REPL) 增强
- 基于 PyPy 代码的新 REPL
- 多行编辑支持
- 彩色提示符和回溯信息
- 交互式帮助 (F1)
- 历史记录浏览 (F2)
- 粘贴模式 (F3)
- 直接 REPL 命令支持
# 示例:新的 REPL 特性
>>> help # 显示帮助信息
>>> exit # 退出解释器
>>> # 支持多行编辑
... def hello():
... print("Hello, World!")
- 错误信息改进
- 彩色回溯信息(可通过环境变量控制)
- 更智能的模块冲突提示
- 关键字参数建议
# 示例:改进的错误提示
def greet(name, age):
pass
# 旧版本
greet(nam="Alice") # TypeError: greet() got an unexpected keyword argument 'nam'
# 新版本
greet(nam="Alice") # TypeError: greet() got an unexpected keyword argument 'nam'. Did you mean 'name'?
- 实验性特性
- 自由线程 CPython (PEP 703)
# 需要特殊构建和运行时标志
# 编译时:--enable-free-threading
# 运行时:PYTHON_GIL=0 或 -X gil=0
import threading
def worker():
# 现在可以真正并行执行
pass
threads = [threading.Thread(target=worker) for _ in range(4)]
for t in threads:
t.start()
- 即时编译器 (JIT) (PEP 744)
# 需要特殊构建和运行时标志
# 编译时:--enable-experimental-jit
# 运行时:PYTHON_JIT=1
# JIT 会自动优化热点代码
def compute():
result = 0
for i in range(1000000):
result += i
return result
- 语言特性
- locals() 确定性突变语义 (PEP 667)
def example():
x = 1
local_vars = locals()
local_vars['x'] = 2 # 不会影响实际的 x
print(x) # 输出: 1
# 使用 f_locals 进行可靠更新
import sys
frame = sys._getframe()
frame.f_locals['x'] = 2 # 会更新 x
print(x) # 输出: 2
- 标准库更新
- argparse 支持弃用选项
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--old-option',
help='Deprecated. Use --new-option instead.',
deprecated=True)
- base64 模块增强
import base64
# 新增 Z85 编码支持
data = b"Hello, World!"
encoded = base64.z85encode(data)
decoded = base64.z85decode(encoded)
性能优化
- 标准库模块导入时间优化
- textwrap.indent() 性能提升(约30%)
- subprocess 模块优化
移除内容
- 完成 PEP 594 "死电池"移除
- aifc
- cgi
- crypt
- nntplib
- telnetlib 等19个模块
- 移除 2to3 工具和 lib2to3 模块
- 移除 tkinter.tix 模块
- 移除 locale.resetlocale() 函数
- 移除 typing.io 和 typing.re 命名空间
- 移除链式 classmethod 描述符支持
- 完成 PEP 594 "死电池"移除
移动平台支持
- 新增 iOS 和 Android 的 Tier 3 级别支持