Python3 new feature Function annotation Function Annotations Usage Analysis, python3annotations
This article analyzes the usage of Function Annotations for new features of python3. We will share this with you for your reference. The details are as follows:
Python 3. X adds a Feature called Function Annotations.
Although its purpose is not a rigid syntax-level requirement, it can be used as an additional comment for functions as its name suggests.
Common functions in Python are defined as follows:
def func(a, b, c): return a + b + c>>> func(1, 2, 3)6
Functions Added with function comments are in the following format:
def func(a: 'spam', b: (1, 10), c: float) -> int: return a + b + c>>> func(1, 2, 3)6
The general rule for annotation is that the parameter name is followed by a colon (:) and then an expression. This expression can be in any form.
The return value is in the form of-> int. annotation can be saved as the attributes of the function.
To view all annotation statements, run the following statement:
>>> func.__annotations__{'c': <class 'float'>, 'a': 'spam', 'b': (1, 10), 'return': <class 'int'>}
If you add comments to the function, can you continue to use the default parameters? The answer is yes.
>>> def func(a: 'spam' = 4, b: (1, 10) = 5, c: float = 6) -> int:... return a + b + c...>>> func(1, 2, 3)6>>> func()15>>> func(1, c=10)16>>> func.__annotations__{'c': <class 'float'>, 'a': 'spam', 'b': (1, 10), 'return': <class 'int'>}