4

New in Python 3.10: 4 Features You Should Try Out

 2 years ago
source link: https://betterprogramming.pub/new-in-python-3-10-4-features-you-should-try-out-d48db504500d
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

New in Python 3.10: 4 Features You Should Try Out

The long-awaited switch statements are finally here!

Opening a gift
Photo by Kira auf der Heide on Unsplash.

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

Multiple Context Managers

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

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

Now, with parenthesized context managers, 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 parentheses:

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 represents the Pythonic way. This is a simple example:

In this case, we are evaluating the name variable. 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:

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

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

Code bases that follow the type hinting paradigm will greatly benefit from this new feature.

Closing Notes

Thank you for reading my article. I hope you enjoyed it. Let me know your favourite features from the latest Python 3.10 update in the comments section!

If you are not caught up with all of the Python updates, check out my review of the Python 3.9 features.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK