Some new features of Python 3.10

Python 3.10.0a2 version has been released on 2020-11-04, so we can get a glimpse of some new features of Python 3.10. These new features are likely to change the future Python ecosystem, making it more clear and readable, while maintaining the ease of use that we know and love.

Thanks to the new release plan: PEP 602 - Annual Release Cycle for Python, we can see a shorter development window, and we are expected to use the new features shared today in October 2021.

PEP 602

1、 Further expansion of type annotations

3.9 The type hints and comments in Python have been greatly revised and cleaned up. Type hints seem to be a continuing trend. It has been further expanded in 3.10. The purpose is obvious. It is for better readability, no need to read The code can know the type of variable and function return value.

Delay execution of type annotations

The operation of type annotations is usually considered to be executed when the function is defined, which means that type annotations are checked line by line in a top-down manner.

Although it seems logical, there are two problems with this:

1、 Type hints (forward references) that refer to undefined types will not work and must be expressed in string form. In other words: if int is a custom type, we need to write "int" instead of writing int.

2、 This will slow down the speed of module import, because type hints are executed at this time.

Therefore, instead of deferred type annotations, type annotations will be stored as strings in __annotations__. If these type annotations are needed, they can be parsed by typing.get_type_hints() at runtime, or by inspect. signature() to analyze immediately. The advantage of this is that module import can be performed first, allowing forward references, thereby reducing initialization time.

**New type comment union operator **

3.10 Use "|" as a logical OR operator. When annotating data types, we can use | as an or. For example, we have a variable that is expected to be int or float, which can be written as int | float as follows:

def f(x: int | float)-> float:return x *3.142f(1)  # pass
f(1.5)  # pass
f('str')  # linter will show annotation error

You can also use the keyword Union provided by the typing module, such as Union[int, float]

TypeAlias Notes

Going back to the problem of forward references, the common solution to avoid forward references is to write them as strings.

However, writing types as strings will cause problems when assigning these types to variables, because Python will assume that our string literal type annotation is just a string.

Using the type annotation variable in the place where type annotation is usually used will return an error. E.g:

MyType ="ClassName"  # ClassName is our type annotation
def foo()-> MyType:...

Here, we are trying to use its MyType as an alias for the type, but MyType will be read as a string value instead of a type alias. As long as the ClassName is defined later in the code, this is valid. In the current situation, this will cause a comment error.

To solve this problem, a method of explicitly identifying MyType as a type alias is added:

from typing_extensions import TypeAlias
MyType: TypeAlias ="ClassName"
def foo()-> MyType:...
OR
MyType: TypeAlias = ClassName # if we have defined ClassName already
def foo()-> MyType:...

Let me talk about why types are important. Although this is certainly not a huge change, it is really cool to see Python developers redouble their efforts to enhance the functionality of types. Python's strengths are its ease of use and lack of a steep learning curve. One of the reasons is that there is no need to explicitly define the type in our code.

Enhanced type annotations may seem counterintuitive, but providing developers with the option of defining types can greatly improve the readability and maintainability of the code base. For example, you can see the following description from the source code of the Python transformers library:

Even without context, we can read this code and immediately grasp what data we should expect to be fed into these functions, classes, and methods — and exactly which datatypes we should be expecting to return.
In complex code bases (and even simple ones), type annotation can massively improve readability. Simultaneously, not everyone will want (or need) to use them — so an optional, exception-free functionality strikes a perfect balance.

This means that even without context, we can read this code and immediately understand what data should be expected to be input into these functions, classes, and methods, and exactly what data types are expected to be returned.

But in complex code bases (even simple code bases), type annotations can greatly improve readability. At the same time, not everyone wants (or needs) to use them, so this is optional. This non-abnormal function can achieve a perfect balance.

These improvements indicate Python's commitment to type annotation capabilities. Based on this, our favorite libraries and our own code can greatly indicate readability, which will have a long-term positive impact on the Python ecosystem.

2、 New functions and changes in function parameters

In addition to the extension of the type hint function, the core Python functions have been updated as follows.

Function zip() adds strict parameter

The function zip() adds the strict parameter. If strict = True is set, and the length of the transmitted parameters is not equal, an exception will be thrown, as shown in the following figure:

The new strict parameter does not blindly truncate unmatched data, but allows us to control its behavior, which will save many developers from trouble.

New integer bit counter int.bit_count()

This new method allows us to count the number of ones in the binary representation of an integer, which is very practical and efficient in certain scenarios.

The result in the above figure is the number of integers whose binary digits are 1:

0=000000001=000000012=000000103=0000001110=0000101011=0000101112=00001100100=01100100101=01100101102=01100110

Add an attribute to the dictionary view

The 3 methods of the dictionary type: dict.items(), dict.keys(), and dict.values() respectively return 3 views of the dictionary. Now each view adds an attribute called mapping. The specific usage is as follows:

The new attribute mapping type belongs to types.MappingProxyType, which is an attribute around the original dictionary. Accessing the mapping attribute on any view will return the original dictionary.

That's it now. Although we are only a few months away from the 3.10 development timeline, there have been many interesting changes. The development of Python is still going on, and it seems that more interesting features will be added to the language.

I hope you like this article, please like, repost, follow, thank you for your support.

Recommended Posts

Some new features of Python 3.10
7 features of Python3.9
Secrets of the new features of Python 3.8
List of new features of Zabbix 5.0 LTS
Some examples of python operation redis
First look at the new features of Ubuntu 17.10
Basics of Python syntax
Basic syntax of Python
Basic knowledge of Python (1)
Prettytable module of python
python download new modules
09. Common modules of Python3
Consolidate the foundation of Python (4)
In-depth understanding of python list (LIST)
Python analysis of wav files
Consolidate the foundation of Python(6)
Analysis of JS of Python crawler
python king of glory wallpaper
Consolidate the foundation of Python(5)
Python implementation of gomoku program
Deep understanding of Python multithreading
Analysis of Python object-oriented programming
Python version of OpenCV installation
9 feature engineering techniques of Python
matplotlib of python drawing module
Python method of parameter passing
Consolidate the foundation of Python (3)
Collection of Python Common Modules
The usage of wheel in python
Summary of logarithm method in Python
Detailed explanation of python backtracking template
Analysis of usage examples of Python yield
Detailed implementation of Python plug-in mechanism
Detailed explanation of python sequence types
Implementation of reverse traversal of python list
Python implementation of IOU calculation case
Magic methods and uses of Python
In-depth understanding of Python variable scope
Python preliminary implementation of word2vec operation
Python handles the 4 wheels of Chinese
Python calculation of information entropy example
Implementation of python selenium operation cookie
Use of numpy in Python development
Python simulation of the landlord deal
What is the use of Python
Scrapy simulation login of Python crawler
Analysis of Python conditional control statements
[Linux] Some high-efficiency tools of Ubuntu
Detailed usage of dictionary in Python
Usage of os package in python
Several common modes of Python functions
A summary of 200 Python standard libraries!
Mongodb and python interaction of python crawler
Implementation of python3 registration global hotkey
Implementation of python student management system
There are several versions of python
Simple usage of python definition class
Summary of Python calling private attributes
​Full analysis of Python module knowledge
Example operation of python access Alipay
The premise of Python string pooling