Member-only story
New in Python 3.10: 4 Features You Should Try Out
The long-awaited switch statements are finally here!
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.