摘要:2020年10月5日,在全国人员欢度国庆节和中秋节时,Python 3.9 悄摸摸地正式公布了。

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.到http://python.org上下载安装包

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

咱们应用第二种办法,安装文件下载链接见 References。

 $ conda create -n py39 -c conda-forge -y    $ conda activate py39    $ conda install python-3.9.0-h60c2a47_1_cpython.tar.bz2         $ which python    /d/Anaconda3/envs/py39/python    $ python -V    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 (|=) 操作符。

 # py38    >>> x = {"key1": "value1 from x", "key2": "value2 from x"}    >>> y = {"key2": "value2 from y", "key3": "value3 from y"}    >>> {**x, **y}    {'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'}    >>> x.update(y)    >>> x    {'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'}         # py39    >>> x = {"key1": "value1 from x", "key2": "value2 from x"}    >>> y = {"key2": "value2 from y", "key3": "value3 from y"}    >>> x | y    {'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'}    >>> y | x    {'key2': 'value2 from x', 'key3': 'value3 from y', 'key1': 'value1 from x'}

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

New string methods to remove prefixes and suffixes

 >>> "NavyXie".removeprefix("Navy")    'Xie'    >>> "NavyXie".removesuffix("Xie")    'Navy'

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

Type hinting generics in standard collections

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

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

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

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

 >>> from dataclasses import dataclass    >>> @dataclass    ... def TestClass:    ...    name: str    ...    >>> TestClass.__annotations__    {'name': <class 'str'>}

这个时候就会比拟有用,咱们能够这样写:

 names: list[str]

而不必像之前那样:

 names: List[str]

新的解析器

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

zoneinfo

这个新模块,在咱们操作时区时,会比拟不便。之前咱们解决timezone时,须要通过pytz包,比方:

 # py38    import pytz    from datetime import datetime         tz = pytz.timezone("America/Los_Angeles")    start_time = datetime.now(tz)

当初能够通过规范库中的zoneinfo模块,比方:

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

其它变动

在python 3.8中,Vectorcall协定被长期引入,3.9中,对内置类型,包含,range, tuple, set, frozenset, list, dict,都应用vectorcall协定进行了优化。但乏味的是,从性能优化报告中,咱们能够看到,从3.8到3.9的性能并没有什么晋升,甚至有小幅降落。

 Python version                       3.4     3.5     3.6     3.7     3.8    3.9    --------------                       ---     ---     ---     ---     ---    ---         Variable and attribute read access:        read_local                       7.1     7.1     5.4     5.1     3.9    4.0        read_nonlocal                    7.1     8.1     5.8     5.4     4.4    4.8        read_global                     15.5    19.0    14.3    13.6     7.6    7.7        read_builtin                    21.1    21.6    18.5    19.0     7.5    7.7        read_classvar_from_class        25.6    26.5    20.7    19.5    18.4   18.6        read_classvar_from_instance     22.8    23.5    18.8    17.1    16.4   20.1        read_instancevar                32.4    33.1    28.0    26.3    25.4   27.7        read_instancevar_slots          27.8    31.3    20.8    20.8    20.2   24.5        read_namedtuple                 73.8    57.5    45.0    46.8    18.4   23.2        read_boundmethod                37.6    37.9    29.6    26.9    27.7   45.9         Variable and attribute write access:        write_local                      8.7     9.3     5.5     5.3     4.3    4.2        write_nonlocal                  10.5    11.1     5.6     5.5     4.7    4.9        write_global                    19.7    21.2    18.0    18.0    15.8   17.2        write_classvar                  92.9    96.0   104.6   102.1    39.2   43.2        write_instancevar               44.6    45.8    40.0    38.9    35.5   40.7        write_instancevar_slots         35.6    36.1    27.3    26.6    25.7   27.7         Data structure read access:        read_list                       24.2    24.5    20.8    20.8    19.0   21.1        read_deque                      24.7    25.5    20.2    20.6    19.8   21.6        read_dict                       24.3    25.7    22.3    23.0    21.0   22.5        read_strdict                    22.6    24.3    19.5    21.2    18.9   21.6         Data structure write access:        write_list                      27.1    28.5    22.5    21.6    20.0   21.6        write_deque                     28.7    30.1    22.7    21.8    23.5   23.2        write_dict                      31.4    33.3    29.3    29.2    24.7   27.8        write_strdict                   28.4    29.9    27.5    25.2    23.1   29.8         Stack (or queue) operations:        list_append_pop                 93.4   112.7    75.4    74.2    50.8   53.9        deque_append_pop                43.5    57.0    49.4    49.2    42.5   45.5        deque_append_popleft            43.7    57.3    49.7    49.7    42.8   45.5         Timing loop:        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

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

(1)Python 3.9 是提供 Python 2向后兼容的最初一个版本,所以在下个版本 Python 3.10 将不在兼容 Python 2。

(2)threading.Thread类的 isAlive() 办法被删除,用is_alive()取代。

(3)base64.encodestring() 和 base64.decodestring() 被删除,用base64.encodebytes() 和 base64.decodebytes() 取代。

(4)json.loads()的encoding参数被删除,encoding必须为UTF-8, UTF-16或UTF-32.

温习 Python 3.8 的几点个性

最初,咱们再温习下 python 3.8 的几点新个性,如果工作中没有尝试过,那就马上试试吧。

  • 海象操作符 :=
 if (n := len(a)) > 10:        print(f"List is too long ({n} elements, expected <= 10)")
  • Positional-only 参数
 def f(a, b, /, c, d, *, e, f):        print(a, b, c, d, e, f)
  • f-string反对 =
 >>> user = 'eric_idle'    >>> member_since = date(1975, 7, 31)    >>> f'{user=} {member_since=}'    "user='eric_idle' member_since=datetime.date(1975, 7, 31)"         >>> delta = date.today() - member_since    >>> f'{user=!s}  {delta.days=:,d}'    'user=eric_idle  delta.days=16,075'         >>> print(f'{theta=}  {cos(radians(theta))=:.3f}')    theta=30  cos(radians(theta))=0.866

References

  • What’s new in python 3.9, https://docs.python.org/3/wha...
  • What’s new in python 3.8, https://docs.python.org/3/wha...
  • Conda-forge python files, https://anaconda.org/conda-fo...
  • Python 3.9 tar, https://anaconda.org/conda-fo...

点击关注,第一工夫理解华为云陈腐技术~