What does -> mean in Python function definitions?

后端 未结 8 1608
我寻月下人不归
我寻月下人不归 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 08:02

    In the following code:

    def f(x) -> int:
        return int(x)
    

    the -> int just tells that f() returns an integer (but it doesn't force the function to return an integer). It is called a return annotation, and can be accessed as f.__annotations__['return'].

    Python also supports parameter annotations:

    def f(x: float) -> int:
        return int(x)
    

    : float tells people who read the program (and some third-party libraries/programs, e. g. pylint) that x should be a float. It is accessed as f.__annotations__['x'], and doesn't have any meaning by itself. See the documentation for more information:

    https://docs.python.org/3/reference/compound_stmts.html#function-definitions https://www.python.org/dev/peps/pep-3107/

提交回复
热议问题