Python 3.9, coming!
Developers from around the world have been working on Python3.8 improvements for the past year. The Python 3.9 beta has been around for some time, with the first official release coming on October 5, 2020.
Each Python release contains newly developed and improved features, and Python 3.9 is no exception.
Python Learning Exchange Group
Here are some of the major new features in Python 3.9.
1. Dictionary (merge & update) operators
Dictionaries are one of the most fundamental data structures in Python, and performance is constantly improved with each iteration of the Python version.
Python3.9, merge (|) and update operator (| =) have been added to the dict class. These updates improve the existing dict.update and {** d1, ** d2} methods.
The traditional way to merge dictionaries is:
>>> Pycon = {2016: "Portland", 2018: "Cleveland"} >> {**pycon, **europython}{2016: 'Portland', 2018: 'Edinburgh', 2017: 'Rimini', 2019: Merged = pycon.copy>>> for key, value in europython.items:... merged[key] = value... >>> merged{2016: 'Portland', 2018: 'Edinburgh', 2017: 'Rimini', 2019: 'Basel'}Copy the code
Both methods merge dictionaries without changing the raw data. Note that the word “Cleveland” in dictionary 1 is overwritten by the word “Edinburgh” in dictionary 2.
You can also update dictionary 1:
>>> pycon.update(europython)>>> pycon{2016: 'Portland', 2018: 'Edinburgh', 2017: 'Rimini', 2019: 'Basel'}
Copy the code
The new version of Python introduces two new dictionary operator: merge (|) and update (| =). You can use | merge two dictionaries, and | = 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'}Copy the code
| d1 and d2 {* * d1, d2} * * works in a similar way, to merge the dictionary and set, meet with the same key, covered in the latter to the former.
Is one of the advantages of using | it is suitable for similar types of dictionary, and keep the original in the combined type:
>>> 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'}
Copy the code
| = role is to update the dictionary, similar to the. 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'}
Copy the code
| = can also be similar to a dictionary of data structure is used to update:
>>> 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'}
Copy the code
2. Delete the string prefix and suffix
In Python 3.9, you can remove the beginning or end of a string using.removeprefix and.removesuffix, 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'
Copy the code
Strip () {strip () {strip ();
>>> "three cool features in Python".strip(" Python")'ree cool features i'
Copy the code
As you can see, I wanted to delete the end of the word python, but the beginning of the word there was also deleted part of the -th.
So.removePrefix and.removesuffix are probably more accurate.
3. Zoneinfo Time zone module
Zoneinfo is a new module introduced in python3.9. Zoneinfo can access the Internet number assignment 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 objects in the database that describe any time zone:
>>> from zoneinfo import ZoneInfo>>> ZoneInfo("America/Vancouver")zoneinfo.ZoneInfo(key='America/Vancouver') >>> from Zoneinfo import zoneinfo >>> from datetime import datetime, timedelta>>> # DST >>> dt = datetime(2020, 10, 31, 12) Tzinfo =ZoneInfo("America/Los_Angeles") >>> print(dt)2020-10-31 12:00:00-07:00>>> dt. Tzinfo 'PDT'>>> # timedelta(days=7)>>> print(dt)2020-11-07 12:00:00-08:00>>> print(dt.tzname)PSTCopy the code
4. Built-in collection types are used for type hints
In type prompts, you can now use built-in collection types (such as List and dict) as generic types instead of importing 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)
Copy the code
5. Topology sort
Python 3.9 graphlib added a new module, which contains graphlib. TopologicalSorter class, to perform the function of the topological sort.
>>> dependencies = {... "realpython-reader": {"feedparser", "html2text"},... "feedparser": {"sgmllib3k"},... }... >>> from graphlib import TopologicalSorter>>> ts = TopologicalSorter(dependencies)>>> list(ts.static_order)['html2text', 'sgmllib3k', 'feedparser', 'realpython-reader']Copy the code
6. Least Common Multiple (LCM)
Python has long had functionality for computing the greatest common divisor (GCD) of two numbers:
>>> import math>>> math.gcd(49, 14)7
Copy the code
The least common multiple (LCM) is related to the greatest common divisor (GCD), and 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)98Copy the code
In Python 3.9, instead of defining your own LCM function, it added the ability to calculate the least common multiple:
>>> import math>>> math.lcm(49, 14)98
Copy the code
7. More powerful Python parser
One of the coolest features in Python 3.9 is one that people don’t notice in everyday programming, which is the parser update. The parser is an essential 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 was implemented based on PEG (Parsing expression Grammar), not LL(1). The performance of the new parser is comparable to that of the old one, and PEG is more flexible than LL(1) when designing new language functionality.
Across the standard library, the PEG parser is slightly faster, but also uses more memory. In fact, it’s hard to get a sense of performance when using a new parser.
Reference: RealPython, Python documentation