Python combat from entry to the master Part 12 - increase the meta-information to the function parameters

Written a function, and then want to add some additional information for the parameters of this function, so other users will be able to know exactly how this function should be used.

Use the function parameter annotation is a good idea, it should prompt the programmer how to correctly use this function. For example, the following have been annotated a function:

def add(x:int, y:int) -> int:
    return x + y

python interpreter does not add any semantics for these annotations. They are not the type of inspection, before the effect of annotated with no run-time and there is no gap. However, for those who read the source code would be helpful in terms of friends. Third-party tools and frameworks might add these semantic annotations. At the same time they will also appear in the document.

>>> help(add)
Help on function add in module __main__:
add(x: int, y: int) -> int

Although you can use any type of object function to add annotations (such as numbers, strings, etc. object instance), but generally speaking class or use string would be better point.

Function annotations are stored only in the function of the  __annotations__ property. E.g:

>>> add.__annotations__
{'y': <class 'int'>, 'return': <class 'int'>, 'x': <class 'int'>}

 

Published 342 original articles · won praise 170 · views 500 000 +

Guess you like

Origin blog.csdn.net/qq_32146369/article/details/104218852