来喽,来喽,Python 3.9正式版发布了

网友投稿 668 2022-05-30

2020年10月5日,在全国人员欢度国庆节和中秋节时,Python 3.9 悄摸摸地正式发布了。我们来一起来看看,这个版本有哪些好玩的新特性,以及对我们部门目前的产品可能会带来哪些影响。

因为jupyter notebook/lab等工具还没有相应适配到python 3.9,所以我们还无法使用,因此本文就使用python 的交互行来演示。

Python 3.9 官方文档,What’s New in Python 3.9,其文字组织的很好,我们接下来也按照这个顺序来讲解,依次是,release highlights, new features, new modules, improve modules, optimizations, deprecated, removed.

大家注意看下,这个文字组织顺序,其实在我们产品发布时,也是适用的。先讲这个版本有什么吸引人的highlights,然后介绍新版本的新内容,最后介绍deprecated / removed,提醒大家升级时需要注意什么,条理很清晰。

安装

到2020年10月9日为止,anaconda上还没有任何channel支持对python 3.9的直接安装,所以想尝鲜,有2种方法:

1. 到python.org上下载安装包

2. 到anaconda的conda-forge channel下载安装文件

我们使用第二种方法,安装文件下载链接见 References。

1 $ conda create -n py39 -c conda-forge -y 2 $ conda activate py39 3 $ conda install python-3.9.0-h60c2a47_1_cpython.tar.bz2 4  5 $ which python 6 /d/Anaconda3/envs/py39/python 7 $ python -V 8 Python 3.9.0

Release Highlights

Python 3.9 内容包括:

• 3个新的语法特性

• 1个新的内置特性

• 2个新的标准库特性

• 6点解释器提升

• 2个新的库模块

如果把以上所有内容都过一遍,可能需要1-2小时。我们这里就挑一些与我们部门产品开发相关的内容,具体来讲一讲,其它内容如果有兴趣,可以自行去读读。

New Features

Dictionary Merge & Update Operators

dict类提供了merge (|) 和 update (|=) 操作符。

1 # py38 2 >>> x = {"key1": "value1 from x", "key2": "value2 from x"} 3 >>> y = {"key2": "value2 from y", "key3": "value3 from y"} 4 >>> {**x, **y} 5 {'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'} 6 >>> x.update(y) 7 >>> x 8 {'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'} 9  10 # py39 11 >>> x = {"key1": "value1 from x", "key2": "value2 from x"} 12 >>> y = {"key2": "value2 from y", "key3": "value3 from y"} 13 >>> x | y 14 {'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'} 15 >>> y | x 16 {'key2': 'value2 from x', 'key3': 'value3 from y', 'key1': 'value1 from x'}

这在dict操作时,会更方便。

New string methods to remove prefixes and suffixes

1 >>> "NavyXie".removeprefix("Navy") 2 'Xie' 3 >>> "NavyXie".removesuffix("Xie") 4 'Navy'

这在string删除不需要的prefix 或 suffix时,会更方便。

来喽,来喽,Python 3.9正式版发布了

Type hinting generics in standard collections

在type annotation中,可以使用内置的collection类型,如list和dict,而不用导入相应的大写类型,如 typing.List 或 typing.Dict。

1 def greet_all(names: list[str]) -> None: 2 for name in names: 3 print("Hello", name)

Annotation是python 3.0 引入的特征,是做什么用的呢?与Java / C / C++ / Swift等强类型语言不同,Python和JavaScript都是弱类型语言,这里类型annotation并不会在解析或运行时强制要求传参的类型,而只是帮助开发者的代码阅读和维护。

另外,如果我们使用python 3.7引入的库,dataclasses,时,就会发现,type annotation在定义一个data类时,是强制要求的,比如:

1 >>> from dataclasses import dataclass 2 >>> @dataclass 3 ... def TestClass: 4 ... name: str 5 ... 6 >>> TestClass.__annotations__ 7 {'name': }

这个时候就会比较有用,我们可以这样写:

1 names: list[str]

而不用像之前那样:

1 names: List[str]

新的解析器

Python 3.9 开始使用新的解析器,基于 PEG,而取代LL(1)。两者的性能相差不大,但PEG更灵活。从这里我们可以推断,从Python 3.10开始,将会引入更多新的语言特性。

zoneinfo

这个新模块,在我们操作时区时,会比较方便。之前我们处理timezone时,需要通过pytz包,比如:

1 # py38 2 import pytz 3 from datetime import datetime 4  5 tz = pytz.timezone("America/Los_Angeles") 6 start_time = datetime.now(tz)

现在可以通过标准库中的zoneinfo模块,比如:

1 from zoneinfo import ZoneInfo 2  3 tz = ZoneInfo("America/Los_Angeles")

其它变化

• 在python 3.8中,Vectorcall协议被临时引入,3.9中,对内置类型,包括,range, tuple, set, frozenset, list, dict,都使用vectorcall协议进行了优化。但有趣的是,从性能优化报告中,我们可以看到,从3.8到3.9的性能并没有什么提升,甚至有小幅下降。

1 Python version 3.4 3.5 3.6 3.7 3.8 3.9 2 -------------- --- --- --- --- --- --- 3  4 Variable and attribute read access: 5 read_local 7.1 7.1 5.4 5.1 3.9 4.0 6 read_nonlocal 7.1 8.1 5.8 5.4 4.4 4.8 7 read_global 15.5 19.0 14.3 13.6 7.6 7.7 8 read_builtin 21.1 21.6 18.5 19.0 7.5 7.7 9 read_classvar_from_class 25.6 26.5 20.7 19.5 18.4 18.6 10 read_classvar_from_instance 22.8 23.5 18.8 17.1 16.4 20.1 11 read_instancevar 32.4 33.1 28.0 26.3 25.4 27.7 12 read_instancevar_slots 27.8 31.3 20.8 20.8 20.2 24.5 13 read_namedtuple 73.8 57.5 45.0 46.8 18.4 23.2 14 read_boundmethod 37.6 37.9 29.6 26.9 27.7 45.9 15  16 Variable and attribute write access: 17 write_local 8.7 9.3 5.5 5.3 4.3 4.2 18 write_nonlocal 10.5 11.1 5.6 5.5 4.7 4.9 19 write_global 19.7 21.2 18.0 18.0 15.8 17.2 20 write_classvar 92.9 96.0 104.6 102.1 39.2 43.2 21 write_instancevar 44.6 45.8 40.0 38.9 35.5 40.7 22 write_instancevar_slots 35.6 36.1 27.3 26.6 25.7 27.7 23  24 Data structure read access: 25 read_list 24.2 24.5 20.8 20.8 19.0 21.1 26 read_deque 24.7 25.5 20.2 20.6 19.8 21.6 27 read_dict 24.3 25.7 22.3 23.0 21.0 22.5 28 read_strdict 22.6 24.3 19.5 21.2 18.9 21.6 29  30 Data structure write access: 31 write_list 27.1 28.5 22.5 21.6 20.0 21.6 32 write_deque 28.7 30.1 22.7 21.8 23.5 23.2 33 write_dict 31.4 33.3 29.3 29.2 24.7 27.8 34 write_strdict 28.4 29.9 27.5 25.2 23.1 29.8 35  36 Stack (or queue) operations: 37 list_append_pop 93.4 112.7 75.4 74.2 50.8 53.9 38 deque_append_pop 43.5 57.0 49.4 49.2 42.5 45.5 39 deque_append_popleft 43.7 57.3 49.7 49.7 42.8 45.5 40  41 Timing loop: 42 loop_overhead 0.5 0.6 0.4 0.3 0.3 0.3

备注:以上结果是python 官方 benchmark, Tools/scripts/var_access_benchmark.py, 的运行结果,单位为纳秒,硬件为Intel® Core™ i7-4960HQ 处理器,OS为macOS 64-bit。

注意 Deprecated / Removed

我提取了一些与我们部门产品可能相关度比较高的几点:

• Python 3.9 是提供 Python 2向后兼容的最后一个版本,所以在下个版本 Python 3.10 将不在兼容 Python 2。 • threading.Thread类的 isAlive() 方法被删除,用is_alive()取代。 • base64.encodestring() 和 base64.decodestring() 被删除,用base64.encodebytes() 和 base64.decodebytes() 取代。 • json.loads()的encoding参数被删除,encoding必须为UTF-8, UTF-16或UTF-32.

复习 Python 3.8 的几点特性

最后,我们再复习下 python 3.8 的几点新特性,如果工作中没有尝试过,那就马上试试吧。

• 海象操作符 :=

1 if (n := len(a)) > 10: 2 print(f"List is too long ({n} elements, expected <= 10)")

• Positional-only 参数

1 def f(a, b, /, c, d, *, e, f): 2 print(a, b, c, d, e, f)

• f-string支持 =

1 >>> user = 'eric_idle' 2 >>> member_since = date(1975, 7, 31) 3 >>> f'{user=} {member_since=}' 4 "user='eric_idle' member_since=datetime.date(1975, 7, 31)" 5  6 >>> delta = date.today() - member_since 7 >>> f'{user=!s} {delta.days=:,d}' 8 'user=eric_idle delta.days=16,075' 9  10 >>> print(f'{theta=} {cos(radians(theta))=:.3f}') 11 theta=30 cos(radians(theta))=0.866

References

• What’s new in python 3.9, https://docs.python.org/3/whatsnew/3.9.html

• What’s new in python 3.8, https://docs.python.org/3/whatsnew/3.8.html

• Conda-forge python files, https://anaconda.org/conda-forge/python/files

• Python 3.9 tar, https://anaconda.org/conda-forge/python/3.9.0/download/win-64/python-3.9.0-h60c2a47_1_cpython.tar.bz2

Python

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:“非漂”十二年,归来仍少年
下一篇:【OC平台】编解码插件离线开发教程【二】
相关文章