New Python 3.10 Features You Must Try Out

Python is beloved by many data scientists and general-purpose developers for its simplicity and elegance. The latest version of Python, the 3.10 is currently in beta phase, but no new features will be added ahead of its final release in October of 2021. Now is just the time to learn about its new features ahead of schedule.

Multiple context managers

The first on our list is the parenthesized context managers in Python 3.10. As a refresher, context managers are special code constructs that allow simple handling of resources, like files:

with open('output.log', 'rw') as fout:
    fout.write('hello')

Now, with the parenthesized context managers feature, you can use multiple context managers in one with block:

with (open('output.log', 'w') as fout, open('input.csv') as fin):
    fout.write(fin.read())

This feature will be useful for bits of code that work with async resources, as you no longer need to have multiple with statements.

Helpful error messages

The new Python 3.10 update also brings us more helpful error messages. These include SyntaxError, IdentationError, AttributeError, and NameError. For example, when you misspell a variable name, Python will suggest another one:

>>> number_of_cars = 5
>>> number_of_cats
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
NameError: name 'number_of_cats' is not defined. Did you mean: number_of_cars?

The same logic is applied to attributes of objects. If you make a typo in the object’s attribute, the interpreter will try to fix it for you. Other error messages now include missing parenthesis:

users = {'abacaba': '123', 'ozzy': 'qwerty',
print(users)

File "example.py", line 1
    users = {'abacaba': '123', 'ozzy': 'qwerty',
            ^
SyntaxError: '{' was never closed

There are many other improvements to error messages, including missing commas, missing :, messing up = and ==, etc.

Structural pattern matching

This is a big one. We have been asking for a switch statement for a while now, and all that wait was justified. In my opinion, the way these were implemented truly represent the pythonic way. This is a simple example:

name = input()
match name:
    case "Misha":
        return "Hello Misha"
    case "John":
        return "Hello John"
    case _:
        return "Go away"

In this case, we are evaluating the variable name. If it matches "Misha" or "John", a greeting will be returned. All other names will be told to go away. This can be simplified using the | symbol:

match name:
    case "Misha" | "John":
        return f"Hello {name}"
    case "Michelle":
        return "Long time no see, Michelle"
    case _:
        return "Go away"

You can add additional conditions on matches with the if statement:

def get_car_price(make, is_turbocharged):
    match make:
        case "Subaru" if is_turbocharged:
            return 10000
        case "Toyota" if not is_turbocharged:
            return 7500
        case _:
            return 2300

This feature will be particularly useful to those dealing with large, multi-axis data banks to quickly categorize their data.

Type union operator

Many of you probably know that Python supports type hints. They do not guarantee type safety, but serve as a useful tool in development. We will talk specifically about type unions, or matching multiple types for one variable. Before Python 3.10, you had to use the special Union type from typing:

def square_root(number: Union[int, float]) -> Union[int, float]:
    return number ** 0.5

Now, with Python 3.10, you can write:

def square_root(number: int | float) -> int | float:
    return number ** 0.5

This syntax also applies to the isinstance function:

>>> isinstance('abacaba', int | str)
True

Codebases that follow the type hinting paradigm will greatly benefit from this new features.

Closing notes

Thank you for reading my article, I hope you enjoyed it. Let me know in the comments what are your favourite features from the latest Python 3.10 update! If you did not catch up with all of the Python updates, here is my review of the Python 3.9 features

Get new content delivered to your mailbox:

leave a comment