I\'ve recently noticed something interesting when looking at Python 3.3 grammar specification:
funcdef: \'def\' NAME parameters [\'->\' test] \':\' suite
As other answers have stated, the ->
symbol is used as part of function annotations. In more recent versions of Python >= 3.5
, though, it has a defined meaning.
PEP 3107 -- Function Annotations described the specification, defining the grammar changes, the existence of func.__annotations__
in which they are stored and, the fact that it's use case is still open.
In Python 3.5
though, PEP 484 -- Type Hints attaches a single meaning to this: ->
is used to indicate the type that the function returns. It also seems like this will be enforced in future versions as described in What about existing uses of annotations:
The fastest conceivable scheme would introduce silent deprecation of non-type-hint annotations in 3.6, full deprecation in 3.7, and declare type hints as the only allowed use of annotations in Python 3.8.
(Emphasis mine)
This hasn't been actually implemented as of 3.6
as far as I can tell so it might get bumped to future versions.
According to this, the example you've supplied:
def f(x) -> 123:
return x
will be forbidden in the future (and in current versions will be confusing), it would need to be changed to:
def f(x) -> int:
return x
for it to effectively describe that function f
returns an object of type int
.
The annotations are not used in any way by Python itself, it pretty much populates and ignores them. It's up to 3rd party libraries to work with them.