Python 3.9 is here!

It takes about 3 minutes to read this article.

Python 3.9 is here!

In the past year, developers from all over the world have been working on improvements to Python3.8. The Python 3.9 beta version has been around for a while, and the first official version was released on October 5, 2020.

Every Python version contains new developments and improved features, and Python 3.9 is no exception.

Here are some major new features of Python 3.9.

1. Dictionary (merge & update) operator

The dictionary is one of the most basic data structures in Python, and with the iteration of the python version, the performance is continuously optimized.

In Python3.9, the merge (|) and update (|=) operators have been added to the dict class. These updates complete the existing dict.update and {** d1, ** d2} methods.

The traditional method of merging dictionaries:

>>> pycon ={2016:"Portland",2018:"Cleveland"} #Dictionary 1>>> europython ={2017:"Rimini",2018:"Edinburgh",2019:"Basel"} #Dictionary 2

# method one
>>>{**pycon,**europython}{2016:'Portland',2018:'Edinburgh',2017:'Rimini',2019:'Basel'}

# Method Two
>>> merged = pycon.copy()>>>for key, value in europython.items():...     merged[key]= value
...>>> merged
{2016:' Portland',2018:'Edinburgh',2017:'Rimini',2019:'Basel'}

Both of these methods incorporate dictionaries without changing the original data. Please note that "Cleveland" in dictionary 1 has been overwritten by "Edinburgh" in merged dictionary 2.

You can also update dictionary 1:

>>> pycon.update(europython)>>> pycon
{2016:' Portland',2018:'Edinburgh',2017:'Rimini',2019:'Basel'}

The new version of Python introduces two new dictionary operators: merge (|) and update (|=). You can use | to merge two dictionaries, while |= is used to update the dictionary:

>>> pycon ={2016:"Portland",2018:"Cleveland"}>>> europython ={2017:"Rimini",2018:"Edinburgh",2019:"Basel"}>>> pycon | europython  #merge
{2016:' Portland',2018:'Edinburgh',2017:'Rimini',2019:'Basel'}>>> pycon |= europython #Update
>>> pycon
{2016:' Portland',2018:'Edinburgh',2017:'Rimini',2019:'Basel'}

d1|d2 and {** d1, ** d2} have similar functions. Both are used to merge dictionaries and take the union. When the same key is encountered, the latter will overwrite the former.

One of the advantages of using | is that it is suitable for dictionary-like types and keeps the original type after merging:

>>> from collections import defaultdict
>>> europe =defaultdict(lambda:"",{"Norway":"Oslo","Spain":"Madrid"})>>> africa =defaultdict(lambda:"",{"Egypt":"Cairo","Zimbabwe":"Harare"})>>> europe | africa
defaultdict(<function<lambda> at 0x7f0cb42a6700>,{'Norway':'Oslo','Spain':'Madrid','Egypt':'Cairo','Zimbabwe':'Harare'})>>>{**europe,**africa}{'Norway':'Oslo','Spain':'Madrid','Egypt':'Cairo','Zimbabwe':'Harare'}

|= The role is to update the dictionary, similar to .update():

>>> libraries ={..."collections":"Container datatypes",..."math":"Mathematical functions",...}>>> libraries |={"zoneinfo":"IANA time zone support"}>>> libraries
{' collections':'Container datatypes','math':'Mathematical functions','zoneinfo':'IANA time zone support'}

|= You can also use a dictionary-like data structure for updates:

>>> libraries |=[("graphlib","Functionality for graph-like structures")]>>> libraries
{' collections':'Container datatypes','math':'Mathematical functions','zoneinfo':'IANA time zone support','graphlib':'Functionality for graph-like structures'}

2. Remove string prefix and suffix

In Python 3.9, you can use .removeprefix() and .removesuffix() to remove the beginning or end of a string, respectively:

>>>" three cool features in Python".removesuffix(" Python")'three cool features in'>>>"three cool features in Python".removeprefix("three ")'cool features in Python'>>>"three cool features in Python".removeprefix("Something else")'three cool features in Python'

Some people will say that the .strip method is also possible, but this method will be deleted by mistake:

>>>" three cool features in Python".strip(" Python")'ree cool features i'

As you can see, I obviously want to delete the ending word python, but the beginning there is also deleted part of -Th.

So .removeprefix() and .removesuffix() may be more accurate.

3. zoneinfo time zone module

zoneinfo is a newly introduced module in python3.9, zoneinfo can access the Internet Assigned Numbers Agency (IANA) time zone database. IANA updates its database several times a year, which is the most authoritative source of time zone information.

Using zoneinfo, you can obtain objects describing any time zone in the database:

>>> from zoneinfo import ZoneInfo
>>> ZoneInfo("America/Vancouver")
zoneinfo.ZoneInfo(key='America/Vancouver')
>>> from zoneinfo import ZoneInfo
>>> from datetime import datetime, timedelta

>>> # summer time
>>> dt =datetime(2020,10,31,12, tzinfo=ZoneInfo("America/Los_Angeles"))>>>print(dt)2020-10-3112:00:00-07:00>>> dt.tzname()'PDT'>>> #standard Time
>>> dt +=timedelta(days=7)>>>print(dt)2020-11-0712:00:00-08:00>>>print(dt.tzname())
PST

4. Built-in collection types are used for type hints

In type hinting, you can now use the built-in collection types (such as list and dict) as generic types without having to import the corresponding uppercase types (such as List or Dict) from typing.

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

5. Topological sort

Python 3.9 adds a new module, graphlib, which contains the graphlib.TopologicalSorter class to provide functions for performing topological sorting.

>>> dependencies ={..."realpython-reader":{"feedparser","html2text"},..."feedparser":{"sgmllib3k"},...}...>>>from graphlib import TopologicalSorter
>>> ts =TopologicalSorter(dependencies)>>>list(ts.static_order())['html2text','sgmllib3k','feedparser','realpython-reader']

6. Least Common Multiple (LCM)

Python has long been used to calculate the greatest common divisor (GCD) function of two numbers:

>>> import math
>>> math.gcd(49,14)7

The least common multiple (LCM) is related to the greatest common divisor (GCD). LCM can be defined according to GCD:

>>> def lcm(num1, num2):...if num1 == num2 ==0:...return0...return num1 * num2 // math.gcd(num1, num2)...>>>lcm(49,14)98

In Python 3.9, you no longer need to define your own LCM function, it adds the function of calculating the least common multiple:

>>> import math
>>> math.lcm(49,14)98

7. A more powerful Python parser

One of the coolest features of Python 3.9 is a feature that you don't notice in daily programming, and that is the update of the parser. The parser is the basic component of the Python interpreter. In the latest version, the parser has been rebuilt.

Python has previously used the LL(1) parser to parse source code into a parse tree. You can think of the LL(1) parser as a parser that reads one character at a time and interprets the source code without backtracking.

The new interpreter is based on PEG (parsing expression grammar), not LL(1). The performance of the new parser is comparable to that of the old parser. PEG is more flexible than LL(1) when designing new language functions.

In the entire standard library, the PEG parser is slightly faster, but it also uses more memory. In fact, when using a new parser, it is difficult to perceive the performance.

Reference: realpython, python documentation

Recommended reading

1

[ Why doesn't Python support the switch statement? ](http://mp.weixin.qq.com/s?__biz=MzIzNzA4NDk3Nw==&mid=2457741065&idx=2&sn=2a44ea68909191d695bb4b018e2df947&chksm=ff448f57c8330641262bf5155c2fa04946d88d163099d778redirecta69d2abf5155c2fa04946d88d163099d#

2

[ Linux! Why did he write such a strong system alone, but China can't do it? ](http://mp.weixin.qq.com/s?__biz=MzIzNzA4NDk3Nw==&mid=2457741059&idx=1&sn=db9004aa4d26a165a9a55dc0542b221a&chksm=ff448f5dc833064b52ff88988562a111aff833064b52ff88988562a111aff3909b89326e776edirect

3

Wonderful tricks: copy the text of the server to the local computer in ssh

4 ‍‍

[ Super complete! I have sorted out 200 standard libraries of Python](http://mp.weixin.qq.com/s?__biz=MzIzNzA4NDk3Nw==&mid=2457741042&idx=1&sn=5c25ce6562e1611691d59499c8db3a89&chksm=ff78eaccenebc26df78eacc8317130f3dscene26dv78eacc83e5146f3dscene#96f8d

Recommended Posts

Python 3.9 is here!
Why python is popular
Python is short-crawling music
Python is slowly fading
Is python an interpreted language?
Is python an interpreted language
Python is short-world epidemic map
Python is short _SVM test
Is python code case sensitive
What is introspection in python
What is object-oriented in python
What is Python variable scope
What is list comprehension in python
Is there function overloading in python
Python deep copy is not perfect
Python judges that it is empty
Python is a cross-platform language code
What is the use of Python
Is python language free or paid?
Everything in Python is an object
Is python suitable for data mining
Is python crawler easy to learn
Python multithreading
Python CookBook
Is there an algorithm in python language
Python3 dictionary
Python3 module
python (you-get)
Python string
Python basics
Python descriptor
Python basics 2
What is the scope of python variables
Python exec
Python notes
Python3 tuple
CentOS + Python3.6+
Python advanced (1)
Python decorator
Python IO
Python multithreading
What is the id function of python
Python toolchain
What is an anonymous function in Python
Python3 list
Python multitasking-coroutine
Python overview
python introduction
Python analytic
Python basics
Where is the pip path of python3
07. Python3 functions
Python basics 3
Python multitasking-threads
What system is good for self-study python
What is the prospect of python development
What is a sequence table in Python
Python functions
python sys.stdout
Is a number in python a variable type
python operator