Python 3.9: Everything you Need to Know

Hiral Thaker

By : Hiral Thaker

Python 3.9: Everything you Need to Know1

Python 3.9 is finally here, and developers love the new set of features. Like every release this year, the performance of the programming language has increased, but there are also plenty of other new features that make this release amazing. According to Statista, Python is one of the top 5 most useful programming languages. The demand for Python is so much that there are plenty of Python developers trying to build intuitive and interactive applications using it. Let’s dig into the latest features of Python 3.9.

Latest Python 3.9 Features:

 

Dictionary Update and Merge Operators:

In the latest release, there are two new built-in operators added in “dict” class, i.e., “|” and “|=”. The former is useful to merge dictionaries, whereas the latter is useful to update the dictionary.

Merge:

Merge

Update:

Update

While updating the key rule is to remember that if there are any key conflicts, it chooses the right most value and removes duplicate data. This update helps in overcoming the previous drawback of adding extra lines of code. Previously, if you wanted to update any variable, then you had to use “first_dict.update (second_dict)”, this operation would modify the entire “first_dict”. To solve this problem, developers had to transfer the value of “first_dict” into a temporary variable and then update it; as a result, it required an extra line of code.

Another method is {**first_dict, **second_dict}, here it is difficult to understand the intent of the code, and its mapping types get ignored as well. Hence, resulting in more confusion and extra lines of code. But, with the latest updates, you can easily use the built-in operations and merge or update the variable without any extra lines of code or unknown intent.

Better Performance PEG Parser:

The latest version of Python replaces the existing LL(1) based Python parser with the new PEG-based Parser as it is high in performance and stable. The CPython parser and grammar is LL(1) and uses a top-down parser approach. Additionally, it parses the inputs from left to right and uses context-free grammar; as a result, it does not consider the context of tokens.

The new PEG parser uplifts grammar restrictions and will reduce the maintenance cost of the language. The major benefit of the PEG parser is, it is extensively tested, validated, and has high performance. Additionally, it also increases 10% of memory and speed consumption of the current parser. In simple terms, the new parser helps to interpret, compile, and run code much faster, which helps in faster development and speed at proper memory management.

New String Functions:

There are two new functions in the “str” object to remove prefixes and suffixes of strings.

  • To remove prefix:str.removeprefix(prefix)
  • To remove suffix:str.removesuffix(suffix)

One of the common tasks in data science applications involves manipulating text to remove prefix/suffix of strings. With the new built-in string operations, we can use indexes with the colon and return a subset of the string – this is known as slicing a string. These functions are part of the standard library and can get you a consistent API that is less fragile, high-performance, and descriptive.

Type Hinting for Built-in Generic Type:

With this release, you can easily have generic types of data by removing parallel type hierarchy in Python. This release supports generic syntax in all standard collections, which are currently available in the typing module. We can use “list” or “dict” built-in collection types as generic data types instead of using “typing.List or typing.Dict”. As a result, the code looks cleaner and is easy to understand and explain. Parameterized generic is an instance of a generic with expected types for container elements.

Support for IANA Time Zone:

In this release, a new module named “zoneinfo” supports the IANA time zone database. The IANA time zones are often called “tz” or “zone info”. There are many IANA time zones with different search paths to specify the IANA timezone to date and time object. For example, we can pass in the name of the search path as the continent/city to the “datetime” object to set its “tzinfo”. So, now developers can easily use this in-built function to fetch time zones.

Cancel Concurrent Features:

The latest release has a new parameter “cancel_feature” which is added to “concurrent.futures.Executor.shutdown()”. This parameter cancels all the pending futures which have not been started yet.

In the previous version, the process would have to wait to complete before shutting down the executor but with the new parameter “cancel_futures” added to both “ThreadPoolExecutor” and “ProcessPoolExecutor”. So, when the parameter value is true, all pending futures will cancel when you call shutdown() function. When you call the shutdown() function, the interpreter checks if the executor is not garbage collected, but if it is in the memory, it gets all the pending work items and cancels futures.

AsyncIO and Multiprocessing Improvements:

In this release, “reuse_address” parameter of “asyncio.loop.create_datagram_endpoint()” is not supported any longer due to security reasons. Another important factor is not using “coroutines, shutdown_default_executor()” so “coroutines, async.to_thread()” are added. The “shutdown_default_executor()” schedules a shutdown for the default executor that waits on the “ThreadPoolExecutor” to finish closing. The “asyncio.to_thread()” is mainly useful for running IO-bound functions in separate threads to avoid blocking the event loop.

With the help of multiprocessing library improvements, a new method close() is added to the “multiprocessing.SimpleQueue” class, which is useful to close the queue. The main thing here is that you cannot call methods get(), put(), empty() once the queue closes.

Random Byte Generation:

A new function in this release is random.Random.randbytes() which is used to generate random numbers. Before this, if developers had to generate random numbers, they had to use other methods like os.getrandom(), os.urandom(), or secrets.token_bytes(), but they could not generate pseudo-random patterns.

For example, you can generate random numbers with expected behavior, and the process is reproducible, so you will have to mostly use seed with random.Random module. To make this process simpler, they launched random.Random.randbytes() to generate random bytes in a controlled manner.

Function to Replace a String:

Before Python 3.9 version the “” .replace (“”,s,n), returns an empty string instead of s for all non-zero n. This used to confuse users and cause inconsistent use in applications. With the latest release, this issue has been fixed and is now consistent with “”.replace(“”, s). Developers can provide max replace occurrence arguments, and it replaces a set of characters from the string with a new set of characters. Thus, making the replace string function easy to use and understand.

Read More: NodeJS vs Python

Conclusion:

Python 3.9 is bringing a major change and is making development faster than before for developers. The new built-in functions will make the development process easier, faster and decrease lines of code. Being a Python development company, these features will help our python developers and us develop applications.

Let us know what your favorite feature is on Twitter!

All product and company names are trademarks™, registered® or copyright© trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them.

Get a Free Consultation

    ✓ 100% Guaranteed Security of Your Information