What does -> mean in Python function definitions?

后端 未结 8 1529
我寻月下人不归
我寻月下人不归 2020-11-22 07:29

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

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


        
8条回答
  •  孤街浪徒
    2020-11-22 07:45

    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.

提交回复
热议问题