Python 3.12 新特性全面总结
Python 3.12 新特性全面总结
发布时间:2023 年 10 月 2 日
官方文档:https://docs.python.org/zh-cn/3.12/whatsnew/3.12.html
一、重磅新语法
1. 类型参数语法与type语句(PEP 695)
全新的泛型声明方式,更简洁、更明确:
# 泛型函数(简洁语法)defmax[T](args:Iterable[T])->T:...# 泛型类classlist[T]:def__getitem__(self,index:int,/)->T:...defappend(self,element:T)->None:...# 类型别名(新增 type 语句)typePoint=tuple[float,float]# 泛型类型别名typePair[T]=tuple[T,T]# 带约束的类型变量typeIntOrStr[T:(int,str)]=list[T]# ParamSpec 和 TypeVarTupletypeIntFunc[**P]=Callable[P,int]# ParamSpectypeLabeledTuple[*Ts]=tuple[str,*Ts]# TypeVarTuple# 带边界约束typeHashableSequence[T:Hashable]=Sequence[T]优势:
- 类型参数作用域清晰(
[T]内可见) - 延迟求值:类型别名可引用后续定义的类型
- 无需
TypeVar,语法更直观
2. f-string 语法松绑(PEP 701)
Python 3.12 解除了 f-string 的诸多限制,现在可以:
1) 复用引号
# 之前(3.11)报错f"This is the playlist: {",".join(songs)}"# 现在(3.12)正常f"This is the playlist: {",".join(songs)}"# 'This is the playlist: Take me back to Eden, Alkaline, Ascensionism'2) 任意嵌套
# 之前:嵌套深度受限f"""{f'''{f'{f"{1+1}"}'}'''}"""# 现在:可任意嵌套f"{f"{f"{f"{f"{1+1}"}"}"}"}"3) 多行表达式 + 注释
f"This is the playlist: {",".join(['Take me back to Eden',# My, my, those eyes like fire'Alkaline',# Not acid nor alkaline'Ascensionism'# Take to the broken skies at last])}"4) 支持反斜杠和 Unicode 转义
# 反斜杠print(f"Newline: {"\n".join(songs)}")# Unicode 转义print(f"Hearts: {"\N{BLACK HEART SUIT}".join(songs)}")# Hearts: Take me back to Eden♥Alkaline♥Ascensionism二、解释器改进
1. 每解释器独立 GIL(PEP 684)
子解释器现在可以拥有独立的 GIL,充分利用多核 CPU:
# 目前仅通过 C API 可用,Python API 计划在 3.13 提供PyInterpreterConfig config={.check_multi_interp_extensions=1,.gil=PyInterpreterConfig_OWN_GIL,};2. 低开销监控(PEP 669)
新增sys.monitoring模块,近零开销的调试和覆盖率工具:
importsys.monitoring# 监控事件类型# sys.monitoring.events.CALL, RETURN, LINE, EXCEPTION, JUMP, ...3. 列表/字典/集合推导式内联(PEP 709)
推导式不再创建单独函数帧,性能提升最高 2 倍:
# 之前:每次执行创建一个函数对象[x*2forxinrange(1000)]# 现在:直接内联执行,无额外开销注意:traceback 不再显示推导式作为单独帧
三、错误提示继续增强
NameError 智能建议扩展
1) 建议标准库模块
>>>sys.version_info NameError:name'sys'isnotdefined.Did you forget toimport'sys'?2) 实例属性建议
classA:def__init__(self):self.blech=1deffoo(self):somethin=blech# 建议 self.blech>>>A().foo()# NameError 提示 self.xxxNameError:name'blech'isnotdefined.Did you mean:'self.blech'?ImportError 改进
# ImportError 提示拼写>>>fromcollectionsimportchainmap ImportError:cannotimportname'chainmap'from'collections'.Did you mean:'ChainMap'?>>>importa.y.zfromb.y.z SyntaxError:Did you mean to use'from ... import ...'instead?四、标准库重要改进
1.isinstance()协议检查提速
运行时可检查协议(@runtime_checkable)的isinstance()检查提速2-20 倍:
fromtypingimportProtocol,runtime_checkable@runtime_checkableclassClosable(Protocol):defclose(self)->None:...# 现在快 2-20 倍isinstance(f,Closable)2.pathlib.Path支持子类化
classMyPath(Path):defwith_segment(self,segment:str)->"MyPath":returnself/segment新增Path.walk()(类似os.walk()):
fornameinPath(".").walk():print(name)新增case_sensitive参数:
Path("data").glob("*.txt",case_sensitive=False)3.os模块 Windows 增强
# 列出驱动器、卷、挂载点(Windows)os.listdrives()# ['C:\\', 'D:\\']os.listvolumes()# ['\\\\?\\Volume{...}\\']os.listmounts("C:\\")# 挂载点# 更准确的 stat()os.stat(file).st_birthtime# 文件创建时间os.stat(file).st_ctime# 现在也是创建时间(未来会改为元数据变更时间)4.itertools.batched()
批量分组迭代器:
fromitertoolsimportbatchedforbatchinbatched(range(10),3):print(list(batch))# [0, 1, 2]# [3, 4, 5]# [6, 7, 8]# [9]5.math模块增强
importmath math.sumprod([1,2],[3,4])# 1*3 + 2*4 = 11 计算乘积之和(点积)math.nextafter(1.0,2.0,steps=10)# 10 步后的值6.sqlite3命令行界面
python-msqlite3 mydb.db7.uuid命令行界面
python-muuid python-muuid.uuid1 python-muuid.uuid48.statistics.correlation()扩展
支持 Spearman 秩相关:
fromstatisticsimportcorrelation correlation(x,y,method='ranked')# Spearman 相关9.random.binomialvariate()
新增二项分布随机数:
importrandom random.binomialvariate(100,0.5)# n=100, p=0.510.calendar枚举
importcalendar calendar.Month.JANUARY# 1calendar.Day.MONDAY# 0五、类型注解改进
1.typing.override()装饰器(PEP 698)
明确标记方法覆盖父类方法,帮助类型检查器验证:
fromtypingimportoverrideclassChild(Parent):@overridedefmethod(self)->None:# 类型检查器验证是否真的覆盖了...@override# 如果父类没有此方法,类型检查器报错defbad_method(self)->None:...2. TypedDict 注解**kwargs(PEP 692)
fromtypingimportTypedDict,UnpackclassConfig(TypedDict):host:strport:intdefsetup(**kwargs:Unpack[Config])->None:...3. f-string 错误位置更精确
f-string 表达式错误现在能精确定位整行:
# 之前(3.11)(x z y)^^^SyntaxError:f-string:invalid syntax# 现在(3.12)my_string=f"{x z y}"+f"{1+1}"^^^SyntaxError:invalid syntax六、安全与性能
1. 哈希算法更新
hashlib内置的 SHA1、SHA3、SHA2-384、SHA2-512、MD5 实现替换为 HACL* 项目经过形式化验证的代码。
2. Linux perf profiler 支持
python-Xperf program.py# 或PYTHONPERFSUPPORT=1python program.py生成.perf文件,可用perf report分析。
3. 递归限制只影响 Python 代码
内置函数不再受sys.setrecursionlimit()影响,由独立机制保护防止虚拟机崩溃。
4. 栈溢出保护
在支持的平台上实现了栈溢出保护。
七、弃用与移除
正式移除
| 移除内容 | 说明 |
|---|---|
distutils包 | 已弃用,3.12 彻底移除。改用setuptools |
asynchat、asyncore模块 | 已移除,改用asyncio |
imp模块 | 已移除 |
wstr成员 | PEP 623,str 对象减小至少 8 字节 |
不再预装 setuptools
venv创建的虚拟环境不再预装setuptools,如需使用需手动pip install setuptools。
语法警告升级
无效转义序列(如"\d")现在产生SyntaxWarning(之前是DeprecationWarning),未来版本将变为SyntaxError。
八、其他值得关注的变化
语言层面
slice对象可哈希:可用作字典键和集合元素sum()使用 Neumaier 求和:浮点数求和更精确- 推导式中未存储的变量可用于赋值表达式:如
[(b := 1) for a, b.prop in iter] memoryview支持半浮点类型("e"格式码)tarfile提取过滤器:防止路径穿越攻击(3.14 默认开启'data')types.MappingProxyType可哈希:如果底层映射可哈希- GC 不再依赖对象分配:在 eval breaker 上运行
shutil改进
# 新 onexc 参数(替代 onerror)shutil.rmtree(path,onexc=lambdaf,e:handle(e))# which() 在 Windows 上考虑 PATHEXTthreading改进
# 设置所有线程的 trace/profilethreading.settrace_all_threads(func)threading.setprofile_all_threads(func)总结
Python 3.12 的核心亮点:
- 类型参数语法
type语句— 泛型声明更简洁,延迟求值 - f-string 完全松绑— 支持引号复用、多行、注释、反斜杠、嵌套
- 每解释器独立 GIL— 多核利用的里程碑
- 低开销监控 API—
sys.monitoring模块 - 列表推导式内联— 性能提升最高 2 倍
isinstance()协议检查提速 2-20 倍pathlib.Path子类化 +walk()方法- 错误提示继续增强— 标准库建议、
self属性建议
Python 3.12 是一个语言语法和类型系统现代化的版本,f-string 的解放解决了长期痛点,类型语法的简化让泛型编程更直观,同时性能优化继续深入。
参考:Python 3.12 官方文档 - What’s New
内容由 AI 整理生成,内容仅供参考,请仔细甄别。
