Python 3.12新版本更新了啥?
Python 3.12主要更新内容
Python 3.12是在今年的10月2号发布的,主要变化有以下几点:
-
PEP:
- PEP701 优化f-string
- PEP 695 类型形参语法和 type 语句
- PEP 692 用TypedDict标注**kwargs
- PEP 698 覆盖静态类型的装饰器
- PEP 684 每个解释器一个 GIL
智能的报错
Python3.12对NameError, ImportError 和 SyntaxError 这三个异常改进了报错时的原因
在NameError提示原因
举个例子:
1 |
# import sys
|
由于我们没有import sys,所以它会报以下错误:
1 |
Traceback (most recent call last):
|
但是在Python3.12中,我们就能发现它报错时提示了原因:
1 |
Traceback (most recent call last):
|
在报SyntaxError提示原因
1 |
>>> import bs4 from BeautifulSoup
|
在报ImportError时也会提示
1 |
>>> from bs4 import beautifulsoup
|
除此之外,还新增了SyntaxWarning
不是有效转义字符会报SyntaxWarning,而不是DeprecationWarning。
举个例子:
1 |
import re
|
在未来的 Python 版本中会报SyntaxError,而不是SyntaxWarning。
f-string的优化
PEP 701 取消了对f-string使用的一些限制。现在f-string中的表达式部分可以是任何有效的表达式了,包括反斜杠与Unicode转义和多行表达式与注释 等
f-string中可嵌套多个f-string
在f-string中我们可以内嵌多个f-string了
1 |
>>> print(f"{f"{f"{1+3==4}"}"}")
|
多行表达式与注释
现在f-string中不再必须把表达式写在一行内了,且能包含注释
1 |
>>> f"This is the playlist: {", ".join([
|
反斜杠与Unicode字符
现在f-string中可以使用反斜杠和Unicode转义了
1 |
>>> print(f"This is the playlist: {"\n".join(songs)}")
|
类型形参语法和 type 语句
PEP 695 引入了一种新的、更紧凑、更明确的方式来创建 泛型类 和 函数:
1 |
def max[T](args: Iterable[T]) -> T:
|
PEP 695还引入了泛型别名定义的新方法:
1 |
type ListOrSet[T] = list[T] | set[T]
|
用TypedDict标注**kwargs
PEP 692 提供了一种更精确的类型注解方案
举个例子
1 |
from typing import TypedDict, Unpack
|
覆盖静态类型的装饰器
在typing模块中添加了一个typing.override(),被它修饰的方法需要复写其父类的同名方法,它可以让类型检查该方法是否正确复写了父类的方法
举个例子:
1 |
from typing import override
|
每个解释器一个 GIL
PEP 684 主要是给每个子解释器创建 GIL,允许 Python 实现真正的并行处理。目前 Python 3.12 还未引入 no-GIL 构建 。按照计划,Python 团队会在 Python 3.13 中将 no-GIL 构建添加为实验性构建模式
小结
没有小结(
参考
1.https://docs.python.org/3.12/whatsnew/3.12.html
2.https://docs.python.org/3.12/whatsnew/3.12.html#whatsnew312-pep701
3.https://docs.python.org/3.12/whatsnew/3.12.html#whatsnew312-pep692
4.https://docs.python.org/3.12/whatsnew/3.12.html#whatsnew312-pep698
5.https://docs.python.org/3.12/whatsnew/3.12.html#whatsnew312-pep684
6.https://zhuanlan.zhihu.com/p/660125081
7.https://zhuanlan.zhihu.com/p/636946984
更多详细内容请到官方文档What’s New In Python 3.12中查看
- Title: Python 3.12新版本更新了啥?
- Author: 旁白
- Created at: 2023-10-14 12:44:33
- Updated at: 2026-11-08 18:00:00
- Link: https://xn--vfv958a.com/article/python-312新版本更新了啥/
- License: This work is licensed under CC BY-NC-SA 4.0.
Sign in
Authentication required to comment
Delete this comment?