What’s new in Python 3.9

Aniket Kumar
Analytics Vidhya
Published in
5 min readOct 12, 2020

--

https://docs.python.org/3/whatsnew/3.9.html
Its always a good habit to read the documentation for better understanding of the release.
The article explains Python 3.9 Features which will be helpful for the developers and people starting with Python.

Download the latest version using the link given below.
https://www.python.org/ftp/python/3.9.0/python-3.9.0-amd64.exe

Dictionary Union Merge

>> x={"key1":"value1", "key2":"value2"}
>> y={"key3":"value3", "key4":"value4", "key5":"value5"}
>> x|y
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4', 'key5': 'value5'}
>>> y|x
{'key3': 'value3', 'key4': 'value4', 'key5': 'value5', 'key1': 'value1', 'key2': 'value2'}

Strings method to remove prefixes and Suffixes

"remove this".removeprefix("remove")
Output: ' this'
"remove this".removesuffix("this")
Output: 'remove '

Introduction of Zoneinfo Library

The following module has been created to support the Internet Assigned Number Authority. Support for the same has been added to the standard library. datetime.tzinfo.

The default zoneifno uses the system’s time zone data if available, if no system time zone data is available.
If neither system data nor tzdata are available, all call to ZoneInfo will raise ZoneInfoNotFoundError.

from zoneinfo import ZoneInfo
from datetime import datetime, timedelta
dt=datetime(2020,10,31,12, tzinfo("India/Mumbai"))
print(dt)
dt.tzname

aysncio
asyncio.loop.create_datagram_endpoint() no longer supported.
New coroutne shutdown_default_executor() added.
asyncio.PidfdChildWatcher, a linux-specific child watcher implementation that returns file descriptors.

hashlib module supports SHA3 hashes and SHAKE XOF from OpenSSL.
Now this a great thing.
Secure Hash Algorithm 3 is the latest member of the family, first released in 2015. It is totally different from MD5-like structure of SHA-1 and SHA-2.

https://en.wikipedia.org/wiki/SHA-3
Read the article above to get more insight about SHA-3.

ipaddress modules now supports IPV6 addresses, the address can be parsed using ipaddress.IPv6Address.

Addition of HTTP status Code 103 Early hints information response status code is primarily intended to be used with the Link header to allow the user agent to start preloading resources while the server is still preparing a response.

Error 418 is funny one I’m a teapot which is client error response code that the server refuses to brew coffee because it is , permanently a teapot.

graphlib- Functionality to operate with graph-like structure.
Function TopologicalSorted(graph=None)

This is again a great module to understand it, lets understand what is topological sort.
Topological sort ordering of a directed graph is a linear ordering of its vertices such that for every directed edge uv from vertex u to vertex , u comes before v in the ordering.

Topological ordering is possible if and only if the graph has no directed cycles, that it has to be directed acylic graph.

So in Depth First Traversal, we print a vertex and then recursively call the function for its adjacent vertices.
In Topological sorting we need to print the vertex before its adjacent vertex.
Getting to know the implementation of Topological Sorting.

There are various function associated with Graphlib and I highly encourage Users to Contribute to it.

graph = {"D": {"B", "C"}, "C": {"A"}, "B": {"A"}}
ts = TopologicalSorter(graph)
tuple(ts.static_order())
('A', 'C', 'B', 'D')

Random Bytes Generation
Another feature in the 3.9 is in the introduction function random.Random.randbytes()
The above function to generate random bytes, random number generation already existed but 3.9 comes with the new function. It cannot be used for generating security tokens, Users are requested to use secrets.token_bytes() for it.

import random
random.randbytes(5)
b'\xf1\x97\x12\x81\x82'

String replace function fix
Understanding the previous replace function
The syntax for the same was string.replace(prev_value, old_value, count).
Now, this function in python 3.8 returned empty string for all non-zero.
But now in Python 3.9 it returns the string s.

Python 3.9 (String Replace Fixed)
Python 3.8

math.factorial() accepts float value and raise ValueError for negative floats and non-integral. Further math module also support lcm and gcd.
math.gcd() function handles multiple argument. In the previous version, User had to use recursion for using the function for multiple value. But it has been resolved in Python 3.9.

math.lcm() returns the least common multiple specified argument

math.nextafter() return the next floating point value after x towards y.

math.ulp() returns the least significant bit of a float.

isAlive() method has been removed which is used to check if a thread is alive or not. Developers are recommended to used is_alive() instead.

Python 3.9 comes with an increase in speed and performance improvement due to the addition of two new feature.
Improvement of vectorcall protocol which removes temporary object created during call as a result of which a number of Python builtins (range, tuple, set, frozenset, list, dict) have increased performance.
The second increase is due to PEG Parser which enables faster parsing, the performance comes noticeable when dealing with large amount of code.

Relaxation of Decorator in Python.
Decorator can be used to implement logger, timer, format conversion, framework.
A Decorator is a function which takes another function as an argument, which is called a decorated function, and then returns a new function.
The function which is returned replaces or further adds the behavior of the decorated function.

So, its an interesting feature in Python which allows to add functionality to an existing code.
Hence, a Decorator is also called meta-function and using meta-f

About PEG Parser for Cpython

https://www.python.org/dev/peps/pep-0617/
The article explains about LL(1) parser and how the PEG Parser solves the ambiguity.
The LL(1) parser follows a top-down approach that parses the input starting from left to right. There are some rules in the grammar which produced ambiguity which produces empty strings and more, the PEG Parses aims to solve that.

Beside, this Python 3.9 is extending the backward compatibility to the backward layer, to give Project Maintainer more time to shift to Python 3.9.

https://medium.com/@gvanrossum_83706/peg-parsers-7ed72462f97c

https://medium.com/@gvanrossum_83706/building-a-peg-parser-d4869b5958fb

Coming articles.
What is Decorator, Parser PEG and LL(1). As this would require separate post to further understand the topic.

--

--