In this post, we will walk through the various features of Python 3.10 and get an idea of what major changes to expect. Let's go...
1. Structural Pattern Matching
Structural pattern matching is an incredible feature to be added to Python
— truly awesome.
# The variable.
num = 10
# The If-Else Block.
if num == 10:
print("It is 10.")
elif num == 5:
print("It is 5.")
elif num == 1:
print("It is 1.")
else:
print("It is something else")
But now we can use, it is like the switch keyword as we know it in many languages, it is called match:
# The variable.
num = 10
# The Match Block.
match num:
case 10:
print("It is 10.")
case 5:
print("It is 5.")
case 1:
print("It is 1.")
case:
print("It is something else")
2. Parenthesized Context Managers.
A smaller change that stems from a much larger change that appeared with Python 3.9 — the new PEG-based parser.The previous Python parser had many limitations, which restricted the Python devs in which syntax they could allow.Python 3.9’s PEG-based parser removed these barriers, which long-term could lead to more elegant syntax — our first example of this change is the new parenthesized context managers.
with open('f1.txt', 'r') as f1, open('f2.txt', 'w') as f2:
f2.write(f1.read())
Now, we have a better way to do the same but in a new cool syntax.
with (open('f1.txt', 'r') as f1,
open('f2.txt', 'w') as f2):
f2.write(f1.read())
3. More Typing.
Easily the most interesting addition here is the inclusion of a new operator which behaves like an OR logic for types, something which we previously used the Union method for:
from typing import Union
def add(x: Union[int, float], y: Union[int, float]):
return x + y
Now, we don’t need to write from typing import Union, and Union[int, float] has been simplified to int | float — which looks much cleaner:
def add(x: int | float, y: int | float):
return x + y
3. Better Error Messages.
Tell me you didn’t jump right on over to Google the first time you saw:
SyntaxError: unexpected EOF while parsing
It’s not a clear error message, and Python is full of less than ideal error messages. Fortunately, someone noticed — and many of these messages have been improved significantly.
'{' was never closed.