Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k 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 (106k 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

0 votes
2 answers
0 votes
4 answers
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...