My experience with Python 3.9 so far, What I’ve learned.

Tola Ore-Aruwaji
5 min readMay 10, 2021

--

Photo by Max Bender on Unsplash

The Python 3.9 series is the current major release of the Python programming language, and it contains many unique distinctive features and optimizations. The official documentation of this release might be a little complicated looking at it for the first time.

Let’s examine these features, how they work, and when they can be implemented.

  1. Walrus Operator: The very first and the biggest change in Python 3.9 is the Introduction of Walrus Operator it is also called assignment expression and denoted by := Assignment expression allows you to assign and return a value in the same expression. It means that you can assign a value to a variable even when a variable doesn’t exist yet in the context of the expression, rather than a stand-alone statement.

For example, in previous versions of Python, you have a variable as name and you want to assign it a value called book without Walrus Operator.

Want to read this story later? Save it in Journal.

name = 'Book'
print(name)

In Python 3.9, you can use the Walrus Operator to assigns the value and immediately print it out.

print(name:='Book')
  • Another benefit of the Walrus operator is in while loops. You can initialize and update a variable, for example,
//While loop with Walrus Operatorinputs = list()
while (current := input("Write Something: "))
!= "quit":
inputs.append(current)

If you want to write the above While loop statement without the Walrus operator, it goes like this:

//While loop without Walrus Operatorinputs = list()
current = input("Write something:")
while current != "quit":
inputs.append(current)
current = input("Write something: ")

Comparing the two expressions above, you can see that the Walrus operator is very useful when assigning and returning a value to the same expression.

2. Positional-only Arguments: In previous versions of Python, there was no positional-only option for custom functions. It was only specific to built-in functions. In Python 3.9 you can use the slash / symbol to denote that all the arguments before it must be specified by position and not by keyword. Here is an example of Python 3.9

def pow(x, y, z=none, /):
r = x **y
return r if z is None else r%z

In this example, all the arguments are positional. In the previous version of python, Z would be considered a keyword argument. Using positional arguments, you can easily refactor your functions.

3. New precise types: Python is dynamically typed but supports the use of type hints via typing module.
There are four new type hints you can use to allow third-party tools to verify your python programs.

  • Literal type: This helps restricts expressions to a specific value or a list of values not necessarily of the same type. One use case of literal is to be able to precisely add types when string arguments are used to describe specific behavior. Here is an example of a function that is taking the port variable of type integer, and the literal values can be connected and disconnected.
def get_status(port: int) -> Literal['connected', 'disconnected']:
  • TypedDict: The TypedDict feature lets you create a dictionary where the values associated with certain keys are restricted to one or more specific types. Traditionally, dictionaries have been annotated using dict the issue is that this only allowed one type for the keys and one type for the values often leading to annotations like dict into a string.
    For example, consider a dictionary that registers information about Python versions. We will have two keys; the version and the release year
versions = {"version": "3.9", "release_year": 2019}

The value corresponding to version is a string while release_year is an integer value this cannot be precisely represented using dict but with the new TypedDict feature, you can represent it by taking the TypedDict class as the base class and specify the type for the version and release_year keys. The type checker will then be able to surmise py39 into version which is type string while py39 into release_year is an integer.

from typing import TypedDictclass PythonVersion(TypedDict):
version:str
release_year:int
py39 = PythonVersion(version='3.9', release_year=2021)
  • Final: The final decorator and the final type annotation indicated that the decorated and the annotated objects should not be overridden, subclassed are reassigned at any point.

The final decorator that you can apply to classes and methods have specific rules which are; Classes decorated with the final decorator cannot be sub-classed while methods decorated by the final decorator can’t be overridden by a subclass.

4. Debugging Improvements: There are some debugging improvements in Python 3.9 like the improvements in F-string. F-strings were introduced in Python 3.6 and it achieved very high popularity they might be the most common reason for python libraries only being supported on version 3.6 or later. An F-string is a formatted string, you can recognize it by the leading F to a string.
Here is an example using the F-string feature in previous versions of Python. In this code, you defined a variable as my_var and utilized that variable inside the string statement between the curly braces. When you are using F-string, you can enclose variables and even expressions inside curly braces. They will be then evaluated at runtime and included in the string. You can also have several expressions in one string that’s what we have in the existing versions.

my_var = 'Book'
print(f'My name is {my_var}')

In Python 3.9 you can use assignment expression inside F-strings treatment. When implementing this, your assignment expressions should be surrounded by parenthesis. For example, if you have the radius R and F-string as f, you can get the Circumference directly inside the F-strings.

import math
r = 3.9
print(f"Diameter {(diam := 2 * r)}\
gives Circumference\
{math.pi * diam:.2f}")

5. Performance Improvements: There are several optimizations made for Python 3.9 some of that can make your code run faster others reduce the memory footprint. Looking up fields in a name is significantly faster in Python 3.9 as compared with Python 3.7.

From the example below, you can compare the memory-efficient lists in Python 3.7, Python 3.8, and Python 3.9

#Python 3.7
Sys.getsizeof(list(range(2020210)))
Output: 18182008
#Python 3.8
Sys.getsizeof(list(range(2020210)))
Output: 16161736
#Python 3.9
Sys.getsizeof(list(range(2020210)))
Output: 14131426

In python 3.9, it uses about approximately 11% less memory than Python 3.8 and the same with Python 3.7.

Working and implementing new features is very important because it saves you a lot of time while coding and helps you to be more productive.

Enjoyed the read? Leave some ‘claps’ below so others can find this post 🙂

Please leave a comment if you have any thought about the topic

Thanks for reading ❤️

  • You can also reach out to me on Twitter or find me on Github.

📝 Save this story in Journal.

--

--