Things that are good to know about Python 3.9

Photo by David Clode on Unsplash

Python 3.9 was released on October 5th 2020 and I think its following features are good to know about:

There is a new operator for dictionary merges dict_a | dict_b and dictionary updates dicta |= dict_b.

You can now update & merge dictionaries in 3 ways:

# Example: merging meal courses and dish names
meals_on_monday = {'breakfast': 'Cornflakes', 'dinner': 'Rice'}
meals_on_tuesday = {'dinner': 'Fries', 'snack': 'Icecream'}
# For Python version < 3.5: by using dict.update()
meals_on_wednesday = meals_on_monday.copy()
# As of Python 3.5: by unpacking dictionaries
meals_on_thursday = {**meals_on_monday, **meals_on_tuesday}
# As of Python 3.9: by using the merge operator
meals_on_friday = meals_on_monday | meals_on_tuesday
>>> print(meals_on_friday)
{'breakfast': 'Cornflakes', 'dinner': 'Fries', 'snack': 'Icecream'}

The motivation is that 1) dict.update() executes in-place and needs an additional dict.copy() to initialise a separate result dictionary, 2) the notation of unpacking dictionaries is not very intuitive.

For updating dictionaries in-place an alternative Update operator is available as of Python 3.9: meals_on_monday.update(meals_on_tuesday) is equivalent to meals_on_monday |= meals_on_tuesday.

The str.removeprefix() and str.removesuffix() functions have been available to easily remove prefixes and suffixes.

# Example: strip prefix
some_string = "ID_123"
prefix = "ID_"
id_without_suffix = some_string.removeprefix(prefix)
>>> print(id_without_suffix)

The motivation for this is that previously you had to do this with some regex replacement function re.sub() or using string.lstrip() by chopping off the number of characters of the prefix, which are both not very intuitive.

Instead of importing type definitions like Dict or List from typing or even mypy, you can now use built-in collection types like dict or list.

def keys_to_list(a_dict: dict[str, str]) -> list[str]:
result = []
for key in a_dict.keys():
return result

Be aware though that the latest mypy 0.790 released October 9th does not support these type definitions yet (relevant Github issue and mypy changelog).

  • If you’re a heavy user of time zone information you might want to check out the addition of the IANA Time Zone database to the standard library in the zoneinfo module. (PEP 615)
  • If you’re codebase stems from Python 2 then be aware that Python 3.9 will be the last version that includes backward compatibility layers for version 2. Make sure to check for DeprecationWarning exceptions while running tests with the -W command-line option.

Check out a list of all changes on the official What’s New In Python 3.9 page. The next Python version 3.10 is expected to be released in a year on October 4th 2021.

Freelance software engineer with a focus on Python and Vue.js