Python 3.12新版本更新了啥?

Python 3.12新版本更新了啥?

旁白
旁白 Lv.5201314

Python 3.12主要更新内容

Python 3.12是在今年的10月2号发布的,主要变化有以下几点:


智能的报错

Python3.12对NameError, ImportError 和 SyntaxError 这三个异常改进了报错时的原因

在NameError提示原因

举个例子:

1
2
3
# import sys
sys.version_info

由于我们没有import sys,所以它会报以下错误:

1
2
3
4
5
Traceback (most recent call last):
File "demo.py", line 1, in <module>
sys.version_info
^^^
NameError: name 'sys' is not defined

但是在Python3.12中,我们就能发现它报错时提示了原因:

1
2
3
4
5
Traceback (most recent call last):
File "demo.py", line 1, in <module>
sys.version_info
^^^
NameError: name 'sys' is not defined. Did you forget to import 'sys'?
在报SyntaxError提示原因
1
2
3
4
5
>>> import bs4 from BeautifulSoup
File "<stdin>", line 1
import bs4 from BeautifulSoup
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Did you mean to use 'from ... import ...' instead?
在报ImportError时也会提示
1
2
3
4
&gt;&gt;&gt; from bs4 import beautifulsoup
Traceback (most recent call last):
File "<stdin>", line 1, in &lt;module&gt;
ImportError: cannot import name 'beautifulsoup' from 'bs4' (...\bs4\init.py). Did you mean: 'BeautifulSoup'?

除此之外,还新增了SyntaxWarning
不是有效转义字符会报SyntaxWarning,而不是DeprecationWarning。
举个例子:

1
2
3
4
5
6
7
import re

# 错误写法:会产生 SyntaxWarning
re.compile("\d+\.\d+")

# 推荐写法:使用原始字符串
re.compile(r"\d+\.\d+")

在未来的 Python 版本中会报SyntaxError,而不是SyntaxWarning。


f-string的优化

PEP 701 取消了对f-string使用的一些限制。现在f-string中的表达式部分可以是任何有效的表达式了,包括反斜杠与Unicode转义和多行表达式与注释 等

f-string中可嵌套多个f-string

在f-string中我们可以内嵌多个f-string了

1
2
&gt;&gt;&gt; print(f"{f"{f"{1+3==4}"}"}")
True
多行表达式与注释

现在f-string中不再必须把表达式写在一行内了,且能包含注释

1
2
3
4
5
6
&gt;&gt;&gt; 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
...])}"
'This is the playlist: Take me back to Eden, Alkaline, Ascensionism'
反斜杠与Unicode字符

现在f-string中可以使用反斜杠和Unicode转义了

1
2
3
4
5
6
&gt;&gt;&gt; print(f"This is the playlist: {"\n".join(songs)}")
This is the playlist: Take me back to Eden
Alkaline
Ascensionism
&gt;&gt;&gt; print(f"This is the playlist: {"\N{BLACK HEART SUIT}".join(songs)}")
This is the playlist: Take me back to Eden♥Alkaline♥Ascensionism

类型形参语法和 type 语句

PEP 695 引入了一种新的、更紧凑、更明确的方式来创建 泛型类 和 函数:

1
2
3
4
5
6
7
8
9
def max[T](args: Iterable[T]) -&gt; T:
...

class list[T]:
def getitem(self, index: int, /) -&gt; T:
...

def append(self, element: T) -&gt; None:
...

PEP 695还引入了泛型别名定义的新方法:

1
type ListOrSet[T] = list[T] | set[T]

用TypedDict标注**kwargs

PEP 692 提供了一种更精确的类型注解方案
举个例子

1
2
3
4
5
6
7
from typing import TypedDict, Unpack

class Movie(TypedDict):
name: str
year: int

def foo(**kwargs: Unpack[Movie]): ...

覆盖静态类型的装饰器

在typing模块中添加了一个typing.override(),被它修饰的方法需要复写其父类的同名方法,它可以让类型检查该方法是否正确复写了父类的方法
举个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from typing import override

class Base:
def get_color(self) -&gt; str:
return "blue"

class GoodChild(Base):
@override # ok: overrides Base.get_color
def get_color(self) -&gt; str:
return "yellow"

class BadChild(Base):
@override # type checker error: does not override Base.get_color
def get_colour(self) -&gt; str:
return "red"

每个解释器一个 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.
Comments

Sign inSign up to comment.

0 Comments
  • Latest
  • Oldest
  • Most liked
Loading comments…
Powered by Django