What does -> mean in Python function definitions?

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

    def f(x) -> 123:
        return x
    

    My summary:

    1. Simply -> is introduced to get developers to optionally specify the return type of the function. See Python Enhancement Proposal 3107

    2. This is an indication of how things may develop in future as Python is adopted extensively - an indication towards strong typing - this is my personal observation.

    3. You can specify types for arguments as well. Specifying return type of the functions and arguments will help in reducing logical errors and improving code enhancements.

    4. You can have expressions as return type (for both at function and parameter level) and the result of the expressions can be accessed via annotations object's 'return' attribute. annotations will be empty for the expression/return value for lambda inline functions.

提交回复
热议问题