0 votes
1 view
in Python by (47.8k points)

I've recently noticed something interesting when looking at the 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 to this syntax explain it?

1 Answer

0 votes
by (107k points)

When you use the ‘->’ in Python function definitions then it is called as a function annotation.

If you are using Python 2.x which has docstrings, so it will allow you to attach a metadata string to various types of object. So this is amazingly handy, When you use Python 3, it extends the feature by allowing you to attach metadata to functions describing their parameters and return values.

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !