入门教程、案例源码、学习资料、读者群
大家好,欢迎来到 Crossin的编程教室 !
本月初,python 3.12 正式发布,现在已经可以从官网下载安装了。
之前有小伙伴反应,Python 官网经常打不开或者下载很慢,所以我们特地下载好了 Python 3.12 的离线安装包,包括 Windows 和 Mac 的,放在了云盘上,有需要的同学可自取。
云盘里还有不少 Python 的学习资料,包括编程教室的教程合集、几本开源电子书、近50个实例代码。
那么 Python 3.12 到底做了哪些更新,又是否值得升级呢?
我们先来看下官方给出的版本更新日志:
给大家翻译一下:
新功能
类型注解
这其中一部分更新对我们写代码来说没有什么影响,比如对 Python 性能的提升,直接就会反应在新版本中,不需要开发者做任何额外的操作。
另外有一些功能,可能我们平常也不太会用到。
本次版本更新体感比较明显的大概是这两样:
下面我们用官方文档中提供的几个示例来简单演示一下。
1. f-string的功能扩展
f-string 是 Python 3.6 开始引入的新特性,它让字符串格式化操作更加丝滑。而现在,它又增加了一些之前不支持的功能。
支持引号中使用同样的引号字符,并且可以无限嵌套
>>> f"{f"{f"{f"{f"{f"{1+1}"}"}"}"}"}"
'2'
支持多行字符串
>>> 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'
支持使用转义字符
>>> 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
2. 错误消息的改进
新版本的报错信息提示更加明确了,甚至还会给出一些建议。
比如提醒你是不是模块没导入
sys.version_info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined. Did you forget to import 'sys'?
是不是成员变量忘了加self
>>> class A:
... def __init__(self):
... self.blech = 1
...
... def foo(self):
... somethin = blech
...
>>> A().foo()
Traceback (most recent call last):
File "<stdin>", line 1
somethin = blech
^^^^^
NameError: name 'blech' is not defined. Did you mean: 'self.blech'?
以及是不是拼写错误
>>> from collections import chainmap
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'chainmap' from 'collections'. Did you mean: 'ChainMap'?
此外,类型注解是 Python 近年来版本更新的重点,从更新日志里把它单独列为一栏就可见一斑。
比如这次又新增了 TypedDict 类型字典对 **kwargs 关键字参数进行更明确的注解:
from typing import TypedDict, Unpack
class Movie(TypedDict):
name: str
year: int
def foo(**kwargs: Unpack[Movie]): ...
调用示例:
def foo(**kwargs: Unpack[Movie]) -> None: ...
movie: dict[str, object] = {"name": "Life of Brian", "year": 1979}
foo(**movie) # WRONG! Movie is of type dict[str, object]
typed_movie: Movie = {"name": "The Meaning of Life", "year": 1983}
foo(**typed_movie) # OK!
another_movie = {"name": "Life of Brian", "year": 1979}
foo(**another_movie) # Depends on the type checker.
那么,我们现在需要更新到 Python 3.12 吗?
我的建议是:
作者:Crossin的编程教室