Krotton Krotton - 25 days ago 6
Python Question

What does -> mean in Python function definitions?

I've recently noticed something interesting when looking at Python 3.3 grammar specification:

funcdef: 'def' NAME parameters ['->' test] ':' suite


The optional 'arrow' block was absent in Python 2 and I couldn't find any information regarding its meaning in Python 3. It turns out this is correct Python and it's accepted by the interpreter:

def f(x) -> 123:
return x


I thought that this might be some kind of a precondition syntax, but:


  • I cannot test x here, at it is still undefined,

  • No matter what I put after the arrow (e.g. 2 < 1), it doesn't affect the function behaviour.



Could anyone accustomed with this syntax explain it?

Answer

It's a function annotation.

In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values.

There's no preconceived use case, but the PEP suggests several. One very handy one is to allow you to annotate parameters with their expected types; it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. Another is to allow parameter-specific documentation instead of encoding it into the docstring.