Python 3.11 新特性全面总结
Python 3.11 新特性全面总结发布时间2022 年 10 月 24 日官方文档https://docs.python.org/zh-cn/3.11/whatsnew/3.11.html一、性能大幅提升Faster CPython 项目Python 3.11 比 3.10快 10-60%标准基准测试平均提速1.25x。主要优化方向启动时间优化更快的函数调用更快的对象创建更高效的字典操作内联缓存优化这是 Python 近年来最显著的性能提升后续版本3.12、3.13将继续深化优化。二、重磅新语法1. 异常组与except*PEP 654支持同时抛出和处理多个无关异常适合并发、批量操作场景# 抛出多个异常exceptions[ValueError(Invalid value),TypeError(Wrong type),RuntimeError(Failed)]raiseExceptionGroup(Multiple errors,exceptions)# 使用 except* 处理异常组try:...except*ValueErroraseg:print(fValueError组:{eg.exceptions})except*TypeErroraseg:print(fTypeError组:{eg.exceptions})异常组特性ExceptionGroup/BaseExceptionGroup异常组类型except*匹配异常组的子组支持嵌套异常组eg.exceptions访问组内所有异常应用场景并发任务中多个任务失败批量操作部分失败多重校验错误收集2. 异常附加备注PEP 678为异常添加上下文信息不改变异常类型try:process_data(data)exceptExceptionase:e.add_note(f处理文件{filename}时失败)e.add_note(f数据大小:{len(data)})raise# 输出示例# Traceback (most recent call last):# ...# ValueError: Invalid data# 处理文件 data.json 时失败# 数据大小: 1024用途添加调试信息记录上下文文件名、行号、用户输入等不需要自定义异常类三、错误定位精确化PEP 657Traceback 现在指向精确的表达式而非整行# 之前3.10Traceback(most recent call last):Filedistance.py,line6,inmanhattan_distancereturnabs(point_1.x-point_2.x)abs(point_1.y-point_2.y)AttributeError:NoneTypeobjecthas no attributex# 现在3.11Traceback(most recent call last):Filedistance.py,line6,inmanhattan_distancereturnabs(point_1.x-point_2.x)abs(point_1.y-point_2.y)^^^^^^^^^AttributeError:NoneTypeobjecthas no attributex复杂表达式示例# 字典访问链return1query_count(db,response[a][b][c][user],retryTrue)~~~~~~~~~~~~~~~~~~^^^^^TypeError:NoneTypeobjectisnotsubscriptable# 算术表达式result(x/y/z)*(a/b/c)~~~~~~^~~ZeroDivisionError:division by zero禁用精确位置减少内存占用python-Xno_debug_ranges script.py# 或PYTHONNODEBUGRANGES1python script.py四、新增标准库模块1.tomllib— TOML 解析PEP 680标准库终于内置 TOML 支持importtomllibwithopen(config.toml,rb)asf:# 注意必须二进制模式configtomllib.load(f)# 或从字符串解析configtomllib.loads( [database] host localhost port 5432 )注意tomllib只支持读取写入需使用第三方库如tomli-w。五、标准库重要改进1.asyncio.TaskGroup— 结构化并发推荐的新并发模式替代create_task()gather()importasyncioasyncdefmain():asyncwithasyncio.TaskGroup()astg:task1tg.create_task(fetch_data(url1))task2tg.create_task(fetch_data(url2))task3tg.create_task(fetch_data(url3))# TaskGroup 退出时自动等待所有任务完成print(task1.result(),task2.result(),task3.result())优势自动等待所有任务自动传播异常使用 ExceptionGroup更清晰的结构化并发2.asyncio.timeout()— 超时上下文管理器importasyncioasyncdefmain():try:asyncwithasyncio.timeout(10.0):awaitlong_running_operation()exceptTimeoutError:print(操作超时)3.asyncio.Barrier— 同步原语importasyncioasyncdefworker(barrier,worker_id):print(fWorker{worker_id}准备就绪)awaitbarrier.wait()print(fWorker{worker_id}开始执行)asyncdefmain():barrierasyncio.Barrier(3)asyncwithasyncio.TaskGroup()astg:foriinrange(3):tg.create_task(worker(barrier,i))4.datetime.UTC— 时区常量fromdatetimeimportdatetime,UTC dtdatetime.now(UTC)# 更简洁# 等价于 datetime.now(timezone.utc)5.datetime.fromisoformat()增强现在支持解析更多 ISO 8601 格式fromdatetimeimportdatetime,date,time datetime.fromisoformat(2024-01-15T10:30:4508:00)date.fromisoformat(2024-01-15)time.fromisoformat(10:30:4508:00)6.math模块新增函数importmath math.exp2(3)# 2^3 8.0math.cbrt(27)# 立方根 3.07.enum模块大幅增强fromenumimportEnum,StrEnum,Flag,auto# StrEnum成员必须是字符串classColor(StrEnum):REDredGREENgreenBLUEblue# Flag 增强支持 len()、迭代、inclassPerm(Flag):Rauto()Wauto()Xauto()pPerm.R|Perm.Wlen(p)# 2list(p)# [Perm.R, Perm.W]Perm.Rinp# True8.hashlib.file_digest()— 文件哈希importhashlibwithopen(large_file.bin,rb)asf:digesthashlib.file_digest(f,sha256)print(digest.hexdigest())9.functools.singledispatch支持联合类型fromfunctoolsimportsingledispatchsingledispatchdefprocess(arg):print(f默认:{arg})process.registerdef_(arg:int|float):print(f数值:{arg})process.registerdef_(arg:list|set):print(f集合:{arg})10.re支持原子分组和占有量词importre# 原子分组 (?...)re.match(r(?a)b,aaab)# 匹配失败时不会回溯# 占有量词 *、、?re.match(ra*b,aaab)# 占有式匹配六、类型注解改进1. 变长泛型PEP 646支持*Ts语法用于不定长类型参数fromtypingimportTypeVarTuple TsTypeVarTuple(Ts)classArray:def__getitem__(self,index:tuple[*Ts])-Array[*Ts]:...2.Self类型PEP 673精确标注返回自身类型的方法fromtypingimportSelfclassShape:defset_scale(self,scale:float)-Self:self.scalescalereturnselfclassCircle(Shape):defset_radius(self,radius:float)-Self:self.radiusradiusreturnself3. TypedDict 字段必需性标记PEP 655fromtypingimportTypedDict,Required,NotRequiredclassPerson(TypedDict):name:Required[str]# 必需age:NotRequired[int]# 可选email:str# 根据 total 决定4. 类型检查辅助函数fromtypingimportassert_never,reveal_type,assert_type,Never# assert_never确认代码不可达类型检查器验证defhandle(value:int|str):ifisinstance(value,int):...elifisinstance(value,str):...else:assert_never(value)# 类型检查器会报错如果有遗漏# reveal_type查看类型检查器推断的类型reveal_type(x)# 类型检查器会输出推断的类型# assert_type验证类型推断assert_type(x,int)# Never永不返回的类型defnever_return()-Never:raiseRuntimeError()5.typing.Any支持子类化fromtypingimportAnyclassDynamicObject(Any):用于 mock 等高度动态的场景pass七、其他语言改进1.for循环支持星号解包forx,*restin[(1,2,3),(4,5,6,7)]:print(x,rest)# 1 [2, 3]# 4 [5, 6, 7]2. 异步推导式嵌套asyncdefprocess():# 外层推导式自动变为异步results[xasyncforxingen()ifawaitcheck(x)]3.-P选项与PYTHONSAFEPATH防止当前目录污染模块导入python-Pscript.py# 或PYTHONSAFEPATH1python script.py这会禁止自动将脚本目录或当前目录添加到sys.path避免恶意模块覆盖。4. 格式化字符串新增z选项将负零转为正零f{-0.0:.2f}# -0.00f{-0.0:.2fz}# 0.005. 整数字符串转换限制防止 DoS 攻击默认限制 4300 位# 超过 4300 位会抛出 ValueErrorint(1*5000)# ValueError# 可通过环境变量调整# PYTHONINTMAXSTRDIGITS0 python script.py # 禁用限制八、弃用与移除重要弃用PEP 594大量遗留标准库模块被弃用将在Python 3.13移除弃用模块说明替代方案cgi、cgitbCGI 支持使用 WSGI 框架audioop音频操作使用第三方库imghdr图像类型识别使用puremagic或filetypemailcapMIME 类型使用mimetypesmsilibWindows 安装器使用第三方工具telnetlibTelnet 协议使用telnetlib3xdrlibXDR 编码使用construct正式移除移除内容说明Py_UNICODE编码器 APIPEP 624bytes在sys.path中3.6 起已失效九、其他值得关注的变化时间精度提升Unixtime.sleep()使用clock_nanosleep()精度 1 纳秒Windows 8.1time.sleep()使用高精度定时器精度 100 纳秒线程锁使用单调时钟threading.Lock.acquire()使用CLOCK_MONOTONIC不受系统时间变化影响。sqlite3增强异常包含 SQLite 扩展错误码sqlite_errorcode、sqlite_errorname新增serialize()/deserialize()数据库序列化与反序列化新增blobopen()增量 I/O 操作新增create_window_function()窗口函数unittest支持上下文管理器importunittestclassMyTest(unittest.TestCase):deftest_something(self):withself.enterContext(some_resource())asr:# 资源自动清理...总结Python 3.11 的核心亮点性能提升 10-60%— 近年来最显著的提速异常组ExceptionGroupexcept*— 处理多个并发异常精确错误定位— Traceback 指向具体表达式异常附加备注— 丰富错误上下文tomllib— 标准库内置 TOML 解析asyncio.TaskGroup— 结构化并发新模式Self类型 — 精确标注返回自身类型Python 3.11 是一个性能与开发体验双提升的版本错误定位改进让调试更轻松异常组让并发错误处理更优雅性能提升让 Python 在更多场景下保持竞争力。参考Python 3.11 官方文档 - What’s New内容由 AI 整理生成内容仅供参考请仔细甄别。