Python 3.9 is here!
Over the past year, developers from all over the world have been working on improvements to Python 3.8. Python 3.9 beta versions have been around for a while, with the first official version released on October 5, 2020.
Every Python version contains newly developed and improved features, and Python 3.9 is no exception.
[python learning exchange group]
The following introduces several major new features of Python 3.9.
Dictionary is one of the most basic data structures in Python, and with the iteration of python versions, 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.
Traditional method of merging dictionaries:
>>> pycon = {2016: "Portland", 2018: "Cleveland"} # 字典1>>> europython = {2017: "Rimini", 2018: "Edinburgh", 2019: "Basel"} # 字典2# 方法一>>> {**pycon, **europython}{2016: 'Portland', 2018: 'Edinburgh', 2017: 'Rimini', 2019: 'Basel'}#方法二>>> merged = pycon.copy>>> for key, value in europython.items:... merged[key] = value...>>> merged{2016: 'Portland', 2018: 'Edinburgh', 2017: 'Rimini', 2019: 'Basel'}复制代码
Both methods merge dictionaries without changing the original data. 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 merge two dictionaries using |
, while |=
is used to update the dictionary:
>>> pycon = {2016: "Portland", 2018: "Cleveland"}>>> europython = {2017: "Rimini", 2018: "Edinburgh", 2019: "Basel"}>>> pycon | europython # 合并{2016: 'Portland', 2018: 'Edinburgh', 2017: 'Rimini', 2019: 'Basel'}>>> pycon |= europython # 更新>>> pycon{2016: 'Portland', 2018: 'Edinburgh', 2017: 'Rimini', 2019: 'Basel'}复制代码
d1|d2
and { ** d1, ** d2}
have similar functions. They are both used to merge dictionaries and take unions. When encountering the same key, the latter will overwrite the former.
One of the advantages of using |
is that it works with dictionary-like types and maintains the original type after merging:
>>> from collections import defaultdict>>> europe = defaultdict(lambda: "", {"Norway": "Oslo", "Spain": "Madrid"})>>> africa = defaultdict(lambda: "", {"Egypt": "Cairo", "Zimbabwe": "Harare"})>>> europe | africadefaultdict(<function <lambda> at 0x7f0cb42a6700>,{'Norway': 'Oslo', 'Spain': 'Madrid', 'Egypt': 'Cairo', 'Zimbabwe': 'Harare'})>>> {**europe, **africa}{'Norway': 'Oslo', 'Spain': 'Madrid', 'Egypt': 'Cairo', 'Zimbabwe': 'Harare'}复制代码
|=
The function 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 dictionary-like data structures 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'}复制代码
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 cause accidental deletion:
>>> "three cool features in Python".strip(" Python")'ree cool features i'复制代码
As you can see, you obviously want to delete the ending word python , but part of the there at the beginning has also been deleted - Th.
So .removeprefix
and .removesuffix
may be more accurate.
zoneinfo is a newly introduced module in python3.9. Zoneinfo can access the Internet Assigned Numbers Authority (IANA) time zone database. IANA updates its database several times a year and is the most authoritative source of time zone information.
Using zoneinfo, you can get an object 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>>> # 夏令时>>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))>>> print(dt)2020-10-31 12:00:00-07:00>>> dt.tzname'PDT'>>> # 标准时间>>> dt += timedelta(days=7)>>> print(dt)2020-11-07 12:00:00-08:00>>> print(dt.tzname)PST复制代码
In type hints, you can now use built-in Collection types (such as list and dict) are used as generic types without having to import the corresponding uppercase type (such as List or Dict) from typing
.
def greet_all(names: list[str]) -> None:for name in names:print("Hello", name)复制代码
Python 3.9 adds a new module graphlib, which contains the graphlib.TopologicalSorter
class to provide the functionality to perform 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']复制代码
Python has long had a function for calculating the greatest common divisor (GCD) of two numbers:
>>> import math>>> math.gcd(49, 14)7复制代码
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:... return 0... 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复制代码
One of the coolest features of Python 3.9 is a feature that people 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 an LL(1) parser as a parser that reads one character at a time and interprets the source code without backtracking.
The new interpreter is implemented based on PEG (parsing expression grammar), not LL(1). The performance of the new parser is comparable to the old parser, and PEG is more flexible than LL(1) when designing new language features.
Of the entire standard library, the PEG parser is slightly faster, however it also uses more memory. In fact, it's hard to tell how good or bad the performance is when using the new parser.
Related free learning recommendations: python tutorial(Video)
The above is the detailed content of Finally Introducing Python 3.9. For more information, please follow other related articles on the PHP Chinese website!