New Features in Python 3.9

Python3.9 is here and brings with it some cool features that you should try now.

Python is a programming language that has increased in popularity because it is easy to read and write; due to this is that each new version seeks ways to improve some of the complexities of how to perform certain operations to make our lives a little easier.

On October 5th was released the stable version of Python 3.9, which brings with it different features, some of which I will introduce below. I also invite you to install it and try it by yourself.

Installation

This installation is performed on Linux to install on another operating system check the Python page.

# 1. Download the python version from the official page into the selected directory.
cd /usr/src
wget https://www.python.org/ftp/python/3.9.0/Python-3.9.0.tgz

#2. Once downloaded, you have to extract its content
sudo tar xzf Python-3.9.0.tgz

# 3. Perform the compilation with the following commands.
cd Python-3.9.0
sudo ./configure --enable-optimizations
sudo make altinstall

# 4. Check that the installation is working.
python3.9 --version

Union Operators in dict

Dictionaries are widely used data structures in Python, and there are different ways in which we can merge or update them; however, these options can be a bit messy:

a = {"name": "Esteban", "lastname": "Solorzano"}
b = {"age": 27}

# Update a dictionary
c = a.copy()
c.update(b)

# Merge dictionaries
c = {
  **a,
  **b
}

There are more ways we could perform these operations; however, these are the ones that I would consider the most common, the first one, and because the update method modifies the dictionary, we should create a copy with the copy() method.

On the other hand, the way I think is the best way (so far) to merge two or more dictionaries requires that we have an understanding of how dictionary unpacking works to generate a new dictionary.

According to PEP 584, we can find two operators that we can use in a cleaner and better way:

a = {"name": "Esteban", "lastname": "Solorzano"}
b = {"age": 27}

# Update a dictionary
a |= b

# Merge dictionaries
c = a | b

These operators work the same way as the previous example, update dictionaries (|=), and merge two or more dictionaries in a new one (|).

New String Methods

Python3.9 includes two new strings methods that allow you to remove prefixes or suffixes. Before looking at how you can use these new methods, let’s see how you could do this in previous versions.

prefix = "test_"
with_prefix = "test_custom_prefix"

print(with_prefix[len(prefix):])


suffix = "_test"
with_suffix = "custom_suffix_test"

print(with_suffix[:-len(suffix)])

These operations are very simple; however, they do not correctly eliminate what we need since it was never validated whether or not it had the prefix or suffix.

prefix = "test_"
with_prefix = "test_custom_prefix"

print(with_prefix.removeprefix(prefix))


suffix = "_test"
with_suffix = "custom_suffix_test"

print(with_suffix.removesuffix(suffix))

The .removeprefix and .removesuffix methods not only take care of removing the information at the beginning or end of a string but before doing so, it checks that it contains the prefix or suffix according to what needs to be removed.

See PEP 616 for full description

Type Hinting Generics In Standard Collections

Because Python is dynamically typed, it can be sometimes confusing to recognize what type of data we are using in our code, that’s where we make use of type hints, which help us understand how our code should work, it is important to emphasize that the type hints will not raise an exception in case of giving a data type that does not match.

from typing import List

numbers: List[int] = [
  1,
  2,
  3
]

name: str = "Esteban"

As you can see some of the type annotations must be imported from typing in their capitalized form, for example (List or Dict).

Now you can use the built-in types like list or dict without importing any annotations.

name: str = "Esteban"
numbers: list[int] = [1, 2, 3]

def main(numbers: list[int]) -> None:
  print(numbers)

See PEP 585 for more details.

New Module zoneinfo

The datetime module allows us to work with dates and times in different ways; however, when it is time to work with time zones we must use third-party libraries to make use of them. PEP 615 details the motivation and proposal that led to the inclusion of this new module which allows us to define time zones based on the IANA database.

import zoneinfo
from datetime import datetime

tz = zoneinfo.ZoneInfo("Asia/Karachi")

now = datetime.now()
now_karachi = datetime.now(tz=tz)

print(now) # 2020-10-08 21:50:59.500258
print(now_karachi) # 2020-10-09 07:50:59.500417+05:00

# To display TZ Database
print(zoneinfo.available_timezones())

Also, the module provides a way to display each of the time zones in the IANA database.

Improvements to existing modules

There have been small improvements in different modules that are currently in the standard python library as:

  • New status code has been added to the http module

  • In the math module three new functions were added and one was improved.

Conclusions

Probably you have never needed any of these features; however, this is a brief introduction to what I think could be the most used in daily life and somehow allow our code to be more and more pythonic.

If you want to know what else this new version has to offer, take a look at the following link.

Python Release Python 3.9.0 Release Date: Oct. 5, 2020 Python 3.9.0 is the newest major release of the Python programming language, and it contains…python.org

No Comments Yet