Python 3.9 features in action
This blog post will teach you how to use some important Python 3.9 features.
Target audience: Python developers looking to quickly learn how they can leverage recent changes in the language.
PEP 584 — Add Union Operators To Dict
Sometimes we need to combine two dicts together. Before, there was not a definitive process for this. The new interface is elegant.
new_dict = dict1 | dict2
Dict union will return a new dict consisting of the left operand merged with the right operand, each of which must be a dict (or an instance of a dict subclass). If a key appears in both operands, the last-seen value (i.e. that from the right-hand operand) wins:
PEP 616 — String methods to remove prefixes and suffixes
These will come in handy. Say you wanted to remove ‘.txt’ from all strings in a list. All you need do is the following:
strings = ["test.txt", "tmp.xml"]strings = [ string.removesuffix('.txt') for string in strings ]
PEP 585 — Type Hinting Generics In Standard Collections
Type hinting makes python code much more readable. With this change, the built-in collections support static typing.
Before Python 3.9
from typing import Listdef greet_all(names: List[str]) -> None:
for name in names:
print("Hello", name)
After Python 3.9
def greet_all(names: list[str]) -> None:
for name in names:
print("Hello", name)
os.pidfd_open()
A new function was added to the os library, os.pidfd_open(). This is a wrapper to the Linux program pidfd_open(2), which allows you to manage processes without race conditions, or signals.
May your programs be bugless.
-Ashton