Python 3.12新版本更新了啥?

Python 3.12新版本更新了啥?

旁白 Lv.5201314

Python 3.12主要更新内容

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


智能的报错

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

在NameError提示原因

举个例子:

demo.py
1
2
3
4
# import sys
sys.version_info


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

terminal
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中,我们就能发现它报错时提示了原因:

terminal
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提示原因
terminal
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时也会提示
terminal
1
2
3
4
>>> from bs4 import beautifulsoup
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'beautifulsoup' from 'bs4' (...\bs4\__init__.py). Did you mean: 'BeautifulSoup'?

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

demo.py
1
2
3
4
import re
re.compile("\d+\.\d+")

SyntaxWarning: invalid escape sequence '\d'

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


f-string的优化

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

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

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

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

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

terminal
1
2
3
4
5
6
>>> 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转义了

terminal
1
2
3
4
5
6
>>> print(f"This is the playlist: {"\n".join(songs)}")
This is the playlist: Take me back to Eden
Alkaline
Ascensionism
>>> 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 引入了一种新的、更紧凑、更明确的方式来创建 泛型类 和 函数:

demo.py
1
2
3
4
5
6
7
8
9
def max[T](args: Iterable[T]) -> T:
...

class list[T]:
def __getitem__(self, index: int, /) -> T:
...

def append(self, element: T) -> None:
...

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

demo.py
1
type ListOrSet[T] = list[T] | set[T]

用TypedDict标注**kwargs

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

demo.py
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(),被它修饰的方法需要复写其父类的同名方法,它可以让类型检查该方法是否正确复写了父类的方法
举个例子:

demo.py
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) -> str:
return "blue"

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

class BadChild(Base):
@override # type checker error: does not override Base.get_color
def get_colour(self) -> 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 中查看

  • 标题: Python 3.12新版本更新了啥?
  • 作者: 旁白
  • 创建于 : 2023-10-14 12:44:33
  • 更新于 : 2024-08-05 06:50:48
  • 链接: https://xn--vfv958a.com/2023/10/14/Python 3.12.0更新内容/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论