Search code examples
pythonfunctionsyntaxreturnparentheses

Best practice for using parentheses in Python function returns?


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.


Solution

  • 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.