0. Tease
You write a function and want to add some extra information to the parameters of the function so that other users know exactly how the function should be used.
Method 1.
Using function parameter annotations is a good way to remind the programmer how to use the function properly. For example, here is an annotated function:
def add(x:int, y:int) - >int:
return x + y
Copy the code
The Python interpreter does not add any semantics to these annotations. They are not type-checked and run the same as before they were unannotated. However, it is useful for those who read the source code. Third-party tools and frameworks may add semantics to these annotations. They also appear in the document.
>>> help(add)
Help on function add in module __main__:
add(x: int, y: int) -> int
>>>
Copy the code
Although you can annotate functions with objects of any type (such as numbers, strings, object instances, etc.), it is generally better to use classes or strings.
Added 2.
Function annotations are stored only in the function’s __annotations__ attribute. Such as:
>>> add.__annotations__
{'y': <class 'int'>, 'return': <class 'int'>, 'x': <class 'int'>}
Copy the code
Although annotations can be used in many ways, their primary purpose is documentation. Because Python does not have a type declaration, it is often difficult to know what arguments to pass to this function just by reading the source code. Using annotations at this point gives the programmer more cues to use the function correctly.
1. Reference
– 1.0: python3 – cookbook. Readthedocs. IO/zh_CN/lates…