Python 3.10 was released on October 4 2021. Today we are going to discuss the features of Python which in my opinion are the top five.
Structural Pattern Matching
Structural pattern matching is one of the most interesting features of Python 3.10. This is equivalent to switch case in other programming languages. The syntax for the same is as follows:
match subject: case <pattern 1>: <code block 1> case <pattern 2>: <code block 2> case <pattern 3>: <code block 3> case _: <default code block>
def print_day(day): match day: case 0: print("monday") case 1: print("tuesday") case 2: print("wednesday") case 3: print("thursday") case 4: print("friday") case 5: print("saturday") case 6: print("sunday") case _: print("not a valid day") for i in range(8): print_day(i)
Output will be :
monday tuesday wednesday thursday friday saturday sunday not a valid day
Parenthesized context managers
In Python 3.10, we can chain multiple context managers in a Parenthesis syntax for the same as follows
with ( contextmanager1(), contextmanager2()): <Block>
with(open('file1.txt') as f1, open('file2.txt') as f2): print(f1.readlines()) print(f2.readlines())
Improved error message
The error message in the new version is more detailed than the previous one. Consider the below example. Now the exact line number is also pointed out in the error message.
def function(): print("hello")
The previous message was
File "inde_error.py", line 2 print("hello") ^ IndentationError: expected an indented block
File "/home/afsal/Desktop/experiments/python310/inde_error.py", line 2 print("hello") ^ IndentationError: expected an indented block after function definition on line 1
The new argument to the zip function
There is a new added argument to zip function. If this is set to true, then both the arguments must have the same length. Otherwise it will throw an error message.
a = [1, 2, 3] b = ["one", "two"] print(list(zip(a, b)))
[(1, 'one'), (2, 'two')]
a = [1, 2, 3] b = ["one", "two"] print(list(zip(a, b, strict=True)))
Traceback (most recent call last): File "/home/afsal/Desktop/experiments/python310/zip_new.py", line 3, in <module> print(list(zip(a, b, strict=True))) ValueError: zip() argument 2 is shorter than argument 1
New Type Union operator
They have added a new type of union operator. This can be done using the | operator. Previously we were using union from typing module
from typing import Union def convert_to_negative(number: Union[int, float]) -> Union[int, float]: return -number
def convert_to_negative(number: int | str) -> int | str: return -number
isinstance(1, int | str)
There are no new modules. But a lot of improvements have been made.
For more details, you may refer to the official documentation.