Details of new features and changes in Python 3.10

  • 2021-11-02 01:55:18
  • OfStack

New Directory Feature 1: Union Operator
New Feature 2: Multiline Context Manager
New feature 3: Structure pattern matching (Structural Pattern Matching)
New change: performance improvement
New change: zip supports length checking

With the release of the last alpha version, the functional changes of Python 3.10 are fully finalized!

Now is the ideal time to experience the new features of Python 3.10! As the title says, this article will share all the important features and changes in Python 3.10.

New feature 1: Union operator

In the past, symbols were used for "arithmetic or" operations, such as:


print(0 | 0)
print(0 | 1)
print({1, 2} | {2, 3})

Output:

0
1
{1, 2, 3}

In Python 3.10, symbols have new syntax, which can represent x type or Y type, replacing the previous typing. Union complete type annotation

Take chestnuts:

The argument to the function should be of type int or str

Old writing:


from typing import Union


def f(value: Union[int, str]) -> Union[int, str]:
    return value*2

New writing:


def f(value: int | str) -> int | str:
    return value*2

This new syntax is also used as the second parameter of isinstance () and issubclass () for type judgment


 isinstance(1086, int | str)   # 10086 Whether it is  int Type   Or  str Type 

New Feature 2: Multiline Context Manager

In the past, Context Manager 1 was generally used for automatic acquisition and automatic release of resources, using Context Manager when opening files:


with open("test.txt", "w") as f:  #  Automatically open and close files 
    f.write("hello ,   I am 3 Wood ")    #   Read and write files 

If you want to copy a file, you need to open the source file and the target file, so you need two context managers, and the code will be written like this:


with open("test.txt", "r") as f:  #  Open the 1 Files 
    with open("test_copy.txt", "w") as f_copy:  #  Open the 2 Files 
        content = f.read()  #  From the first 1 Get the content of files 
        f_copy.write(content)  #  Directional 2 File writes 

In Python 3.10, the code can be reduced by one:


with (
    open("test.txt", "r") as f,  #  Open the 1 Files 
    open("test_copy.txt", "w") as f_copy,  #  Open the 2 Files 
):
    content = f.read()  #  From the first 1 Get the content of files 
    f_copy.write(content)  #  Directional 2 File writes 

Notice the changes:

with only appeared once In the same code snippet, there are two context managers f and f_copy These two context managers can interact

In addition, it can also be more flexible (sao) live (qi) operation:


with (
    open("test.txt", "r", encoding="utf-8") as f,  #  Open the 1 Files 
    open("test_copy.txt", "w", encoding=f.encoding) as f_copy,  #  Open the 2 Files 
):
    content = f.read()  #  From the first 1 Get the content of files 
    f_copy.write(content)  #  Directional 2 File writes 

Note the details: In the second open, the result of the first open is used: f

New feature 3: Structure pattern matching (Structural Pattern Matching)

If you are familiar with or have used languages such as php, Java, or JavaScript, you may see switch statements, such as:


today = new Date().getDay();
switch () {
    case 0:
        day = " Sunday ";
        break;
    case 1:
        day = " Week 1";
         break;
    case 2:
        day = " Week 2";
         break;
    case 3:
        day = " Week 3";
         break;
    case 4:
        day = " Week 4";
         break;
    case 5:
        day = " Week 5";
         break;
    case 6:
        day = " Week 6";
} 

Simply put: According to the value of x, select the specified case statement to execute

In the past, Python didn't have such a statement, so now, there is!


today = 1
match  today:
    case 0:
        day = " Sunday "
    case 1:
        day = " Week 1"
    case 2:
        day = " Week 2"
    case 3:
        day = " Week 3"
    case 4:
        day = " Week 4"
    case 5:
        day = " Week 5"
    case 6:
        day = " Week 6"
    case _:
        day = " Stop it ...1 Only one week 7 Days "

print(day)

Output

Monday

If line 1 is changed to today = 8, the output

Stop it... There are only seven days in a week

Note:

The matching order is from top to bottom When a matching case is found, it will stop, so there is no need to write break statements to JavaScript1 samples If there are more than one eligible case, the subsequent case will not have a chance to match If there is no match that matches the criteria, case_ is executed, which is called a wildcard character, and the wildcard character is optional

As for the structure matching pattern (Structural Pattern Matching), it can be said that it is a heavyweight new function of Python 3.10, and it has many advanced uses, which are worth introducing in a special article, so we will not expand it here.

In a word, as a late "switch", it will be improved on the practical experience in other programming languages to conform to the style of Python1: simple, flexible and powerful.

New change: performance improvement

Like all the latest Python releases 1, Python 3.10 also brings some performance improvements. The first is the optimization of the str (), bytes (), and bytearray () constructors, which should increase their speed by about 30% ~ 40% (from https://bugs. python. org/issue41334)


from typing import Union


def f(value: Union[int, str]) -> Union[int, str]:
    return value*2
0

In addition, there are several Python core modules undergoing continuous optimization, so let's continue to look forward to it

New change: zip supports length checking

PEP 618: The zip () function now has an optional strict flag, which requires all iterable objects to be of equal length

First, review the usage of zip function under 1:

In one iteration, read content to multiple sequences at the same time,

You can turn rows into columns and columns into rows, which is similar to a transpose matrix.


from typing import Union


def f(value: Union[int, str]) -> Union[int, str]:
    return value*2
1

Output


from typing import Union


def f(value: Union[int, str]) -> Union[int, str]:
    return value*2
2

The above example has one characteristic: name_list and number_list are the same length. What if the length is different?


name_list = [' Alarm ', ' First aid ', ' Fire fighting ', ' Check number ']
number_list = [110, 120, 119]

for i in zip(name_list, number_list):
    print(i)

Output


from typing import Union


def f(value: Union[int, str]) -> Union[int, str]:
    return value*2
4

Note: Because the length is different, the last group of results will not be displayed, but there is no hint. From the results, it is impossible to judge whether there are missing data.

In Python 3.10, the parameter strict=True can be passed to zip () to strictly check the length


from typing import Union


def f(value: Union[int, str]) -> Union[int, str]:
    return value*2
5

Output


from typing import Union


def f(value: Union[int, str]) -> Union[int, str]:
    return value*2
6

Note: The second parameter of zip is shorter than the first parameter, so an exception is thrown

These are the details of the new features and changes in Python 3.10. For more information about the new features and changes in Python 3.10, please pay attention to other related articles on this site!


Related articles: