Best practice for using parentheses in Python function returns?

只谈情不闲聊 提交于 2019-12-13 23:09:47

问题


I'm learning Python and, so far, I absolutely love it. Everything about it.

I just have one question about a seeming inconsistency in function returns, and I'm interested in learning the logic behind the rule.

If I'm returning a literal or variable in a function return, no parentheses are needed:

def fun_with_functions(a, b):
    total = a + b
    return total

However, when I'm returning the result of another function call, the function is wrapped around a set of parentheses. To wit:

 def lets_have_fun():
     return(fun_with_functions(42, 9000))

This is, at least, the way I've been taught, using the A Smarter Way to Learn Python book. I came across this discrepancy and it was given without an explanation. You can see the online exercise here (skip to Exercize 10).

Can someone explain to me why this is necessary? Is it even necessary in the first place? And are there other similar variations in parenthetical syntax that I should be aware of?

Edit: I've rephrased the title of my question to reflect the responses. Returning a result within parentheses is not mandatory, as I originally thought, but it is generally considered best practice, as I have now learned.


回答1:


It's not necessary. The parentheses are used for several reason, one reason it's for code style:

example = some_really_long_function_name() or another_really_function_name()

so you can use:

example = (some_really_long_function_name()
           or
           another_really_function_name())

Another use it's like in maths, to force evaluation precede. So you want to ensure the excute between parenthese before. I imagine that the functions return the result of another one, it's just best practice to ensure the execution of the first one but it's no necessary.




回答2:


I don't think it is mandatory. Tried in both python2 and python3, and a without function defined without parentheses in lets_have_fun() return clause works just fine. So as jack6e says, it's just a preference.




回答3:


if you

return ("something,)   # , is important, the ( ) are optional, thx @roganjosh

you are returning a tuple.

If you are returning

return someFunction(4,9) 

or

return (someFunction(4,9))

makes no difference. To test, use:

def f(i,g):    
    return i * g

def r():    
    return f(4,6)

def q():
    return (f(4,6))

print (type(r()))
print (type(q()))

Output:

<type 'int'>
<type 'int'>


来源:https://stackoverflow.com/questions/48328561/best-practice-for-using-parentheses-in-python-function-returns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!