Should a return statement have parentheses?

前端 未结 5 1714
独厮守ぢ
独厮守ぢ 2020-12-08 01:57

Suppose we have in Python 3.x (and I guess in Python 2.6 and in Python 2.7 too) the following functions:

>>> def dbl_a(p): return p*2
>>> d         


        
5条回答
  •  盖世英雄少女心
    2020-12-08 02:37

    7.6. The return statement

    return_stmt ::=  “return” [expression_list]
    

    expression_list

    return may only occur syntactically nested in a function definition, not within a nested class definition.

    If an expression list is present, it is evaluated, else None is substituted.

    return leaves the current function call with the expression list (or None) as return value.

    When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.

    In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised. The returned value (if any) is used as an argument to construct StopIteration and becomes the StopIteration.value attribute.

    In an asynchronous generator function, an empty return statement indicates that the asynchronous generator is done and will cause StopAsyncIteration to be raised. A non-empty return statement is a syntax error in an asynchronous generator function.

    So basically return is a statement with an optional expression list as an argument. Therefore parentheses are not required and only preferrable when necesary (i.e. for breaking precedences).

提交回复
热议问题