- Expert Python Programming(Third Edition)
- Micha? Jaworski Tarek Ziadé
- 187字
- 2021-06-24 14:55:15
The general syntax
A slightly modified example from the Python documentation shows how to define and retrieve function annotations:
>>> def f(ham: str, eggs: str = 'eggs') -> str: ... pass ... >>> print(f.__annotations__) {'return': <class 'str'>, 'eggs': <class 'str'>, 'ham': <class 'str'>}
As we can see, parameter annotations are defined by the expression evaluating the value of the annotation, preceded by a colon. Return annotations are defined by the expression between the colon denoting the end of the def statement and literal -> that follows the parameter list.
Once defined, annotations are available in the __annotations__ attribute of the function object as a dictionary and can be retrieved during application runtime.
The fact that any expression can be used as the annotation and that it is located just near the default arguments allows us to create some confusing function definitions, as follows:
>>> def square(number: 0<=3 and 1=0) -> (\ ... +9000): return number**2 >>> square(10) 100
However, such usage of annotations serves no other purpose than obfuscation, and, even without them, it is relatively easy to write code that is hard to read and maintain.