目录
新特性
增强回溯中的错误位置。
当我们打印tracebacks,解释器现在指出特定表达式引起的错误,而不是仅仅某一行,比如:
Traceback (most recent call last):
File "distance.py", line 11, in <module>
print(manhattan_distance(p1, p2))
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "distance.py", line 6, in manhattan_distance
return abs(point_1.x - point_2.x) + abs(point_1.y - point_2.y)
^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'x'
以前版本的解释器会只指向这一行,使得哪个对象是None变得模糊不清。在处理深度嵌套的字典对象和多个函数调用时,这些增强的错误也会有帮助。
异常情况可以用注释来补充
add_note()
方法被添加到BaseException
中。它可以用来丰富异常的上下文信息,这些信息在异常发生的时候是不可用的。添加的注释会出现在默认的跟踪回溯中。
>>> try:
... raise TypeError('bad type')
... except Exception as e:
... e.add_note('Add some information')
... raise
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: bad type
Add some information
>>>
新的类型标注
将单个TypedDict项目标记为需要或不需要。
Required
和 NotRequired
提供了一种直接的方式来标记 TypedDict
中的各个项目是否必须存在。以前,这只能通过继承来实现。
除非设置了 total=False
参数,否则默认情况下字段仍然是必需的。例如,下面指定了一个有一个必须的和一个非必须的键的 dictionary
。
class Movie(TypedDict):
title: str
year: NotRequired[int]
m1: Movie = {"title": "Black Panther", "year": 2018} # ok
m2: Movie = {"title": "Star Wars"} # ok (year is not required)
m3: Movie = {"year": 2022} # error (missing required field title)
等价于
class Movie(TypedDict, total=False):
title: Required[str]
year: int
新的模块
- 增加了一个新的模块,tomllib,用于解析TOML。
- 优化模块有:
- asyncio
- contextlib
- datetime
- enum
- fractions
- ……
最后
python3.11 官方说比python3.10平均快25%,主要来自
快速启动,在Python 3.11中,解释器的启动速度现在提高了10-15%。这对使用Python的短时运行的程序有很大影响。
快速运行,更便捷的、懒惰的Python框架,优化内嵌的Python函数调用,专业化自适应的解释器。