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
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.
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.
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]
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.
In addition to the extension of the type hint function, the core Python functions have been updated as follows.
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.
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
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