I\'ve recently noticed something interesting when looking at Python 3.3 grammar specification:
funcdef: \'def\' NAME parameters [\'->\' test] \':\' suite
In the following code:
def f(x) -> int:
return int(x)
the -> int
just tells that f()
returns an integer (but it doesn't force the function to return an integer). It is called a return annotation, and can be accessed as f.__annotations__['return']
.
Python also supports parameter annotations:
def f(x: float) -> int:
return int(x)
: float
tells people who read the program (and some third-party libraries/programs, e. g. pylint) that x
should be a float
. It is accessed as f.__annotations__['x']
, and doesn't have any meaning by itself. See the documentation for more information:
https://docs.python.org/3/reference/compound_stmts.html#function-definitions https://www.python.org/dev/peps/pep-3107/