What’s New in Python 3.9?

The first version of Python came in 1991. Since then, there have been two major versions – Python 2 and Python 3. Before 2020, both of these versions were useful to developers and programmers. But now, Python 2 is deprecated. As a result, the Python Software Foundation only supports Python 3. As of writing this article, the latest stable version is Python 3.9.

Python is a regularly updated programming language. Old features are either removed or changed. And with every minor version update, we can see more new features.

Similarly, this version brought many new features and optimizations as well. So, in this article, we will discuss some of the cool features of this version.

Need a little refresher on Python? Check out this cheat sheet for reference:

Make sure to check out this in-depth tutorial on Python from Linkedin Learning:

Anyway, let’s get started.

New Dictionary Operators

Dictionary is one of the most used Python collections. It is different from other collections because it stores data in key-value pairs.

Python 3.9 has two new operators that will simplify updating and merging dictionaries.

Earlier, there was a update() method for updating a dictionary.

Now they introduced the |= operator. The following code shows how to use this operator to update a value in a dictionary.

d = {"name" : "John", "age" : 21}
d |= {"age" : 27}
print(d)

Output:

{'name': 'John', 'age': 27}

If the key is not present in the dictionary, it will append the key and the value to the dictionary.

For example:

d = {"name" : "John", "age" : 21}
d |= {"location" : "New York"}
print(d)

Output:

{'name': 'John', 'age': 21, 'location': 'New York'}

Another new operator in this version is the | operator. You can use this operator to merge dictionaries.

Observe the following code:

d1 = {"name" : "John", "age" : 21}
d2 = {"location" : "New York"}
d3 = d1 | d2
print(d3)

Output:

{'name': 'John', 'age': 21, 'location': 'New York'}

Unlike the |= operator, the | operator returns a new dictionary.

New String Methods

Though Python offers many in-built string methods, the new version added two more. 

These two methods are removeprefix() and removesuffix().

The removeprefix() method removes the prefix of a string. 

st1 = "MyNameIsMirza"
st2 = st1.removeprefix("My")
print(st2)

Output:

NameIsMirza

The removeprefix() method returns a new string with prefix removed. 

If the prefix does not match the specified value, the removeprefix() method will return the original string. 

Similarly, the removesuffix() method removes the suffix from a string.

st1 = "MyNameIsMirza"
st2 = st1.removesuffix("Mirza")
print(st2)

Output:

MyNameIs

Improvements in the Math Module

The math module in Python is one of the most commonly used in-built modules. It provides several crucial methods for programmers to integrate into their application. 

The gcd() and lcm() methods of the math module are common ones to find the greatest common divisor and least common divisor, respectively. But earlier, we could only use two values with these methods. The following code will give an error in Python 3.8.

import math
math.gcd(14,35,70)

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-d0291b5bb868> in <module>()
      1 import math
----> 2 math.gcd(14,35,70)

TypeError: gcd expected 2 arguments, got 3

It happens because 3.8 only allows two arguments for gcd().

But it will work in Python 3.9 because we can pass any amount of number to the method.

import math
math.gcd(14,35,70)

Output:

7

Similarly, we can use more than two arguments with the lcm() method as well.

Improvements in Type Hinting and Annotations

We type in Python dynamically. We do not need to specify the data type of variable in Python. But it is possible to do it, and it is called type hinting.

Observe the following code:

a: int = 100
b: str = "Hello"
c: bool = True

Output:

>>> a: int = 100
>>> b: str = "Hello"
>>> c: bool = True
>>>

This way of declaring data types also works fine in Python 3.8. However, with version 3.8, it is not possible with Python collections.

The following code will throw an error:

l: list[int] = [1, 2, 3, 4, 5]

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-abca55d4f3ec> in <module>()
----> 1 l: list[int] = [1, 2, 3, 4, 5]

TypeError: 'type' object is not subscriptable

But it is possible in Python 3.9.

l: list[int] = [1, 2, 3, 4, 5]
print(l)

Output:

[1, 2, 3, 4, 5]

Python has a feature called annotations through which we can add arbitrary metadata to functions.

Then, Python 3.9 introduced a new module named typing. This module allows us to combine annotations with type hinting.

Observe the following code:

def demo(arg1: "arg1", arg2: "arg2"):
	pass

This way was the old way of using annotations.

from typing import Annotated
def demo( arg1: Annotated[str, "arg1"], arg2: Annotated[str, "arg2"] ):
	pass

By importing Annotated from the typing module, we can provide type hints to the annotations.

The Zoneinfo Module 

Working with time and date can be complicated sometimes. 

Python provides a datetime module for working with time and date. But there is not much support for working with different time zones in Python. 

As a result, working with time zones can be complex. 

Python 3.9 introduced a new module, named zoneinfo, that makes it easier to work with time zones.

The zoneinfo module provides access to the Time Zone databases of Internet Assigned Numbers Authority (IANA). The module provides several methods we can utilize to work with time zones.

Learn more about the zoneinfo module from the official Python 3.9 documentation:

The New Parser

This feature introduced in Python 3.9 does not have anything to do with coding. The older version of Python uses an LL(1) based parser.

Now, Python 3.9 introduced a new high-performant parser. This parser is the PEG-based parser that will completely replace the old parser.

The core Python team ran through extensive tests on the new parser before implementing it with the latest version. In contrast to the older versions, it is validated and gives better performance.

For more information regarding the new parser, you can refer to the following link:

Conclusion

Python 3.9 came out with a lot of added features and improvements. But there are scenarios you should consider if you are trying to upgrade to this version. Especially in terms of any production environment, you should review the exceptions and errors this upgrade may cost.

But trying out new projects with Python 3.9 would not hurt. At least, in my opinion.

In summary, here are the cool new features and points we discussed in this article

  • As of writing this article, Python 3.9 is the last major version of the Python programming language. This version introduced new features and updated the old ones.
  • We saw two new operators for merging and updating dictionaries in this version. They are |+ (for updating) and | (for merging).
  • Two new string methods. They are removeprefix() and removesuffix().
  • Now, gcd() and lcm() methods can have more than two arguments.
  • Python 3.9 made some improvements in type hinting. For example, we can use this feature with collections. 
  • Python 3.9 can integrate type hinting and annotations simultaneously. 
  • The zoneinfo module makes working with zones easy.
  • Lastly, we discussed this version implemented high performing PEG-based new parser.

If you are interested in learning more about how to program in Python, check out the following course from Linkedin Learning:

Learn more about Python 3.9 through interactive video course:

What do you think of Python 3.9? Are you considering an upgrade? If so, why?

Leave a Reply