1

For example, consider the following two functions:

Case 1

def add(number_1, number_2):
    "Adds two numbers."
    result = number_1 + number_2
    return result

Case 2

def add(number_1, number_2):
    "Adds two numbers."
    return number_1 + number_2

I'm just wondering about the best practice here. It seems like Case 1 would be slightly easier to document and debug, especially if the function were more complex than a simple add function (which I realize is not actually a useful function, just needed an example).

Is this something you would determine on a case-by-case basis, or is there some reason you would always want to name your returned value?

quamrana
  • 37,849
  • 12
  • 53
  • 71
Jon Strutz
  • 302
  • 4
  • 9
  • 1
    For the short example you give, there's no need for a "return variable". I would definitely use one in the case where there would otherwise be multiple return statements. I like to have a single return at the end, which makes stuff like memoization of results easier. – Mark Lavin Aug 19 '21 at 16:28
  • 4
    One advantage of naming your return value is that its easier to set a breakpoint or insert a print for debugging. Other than that, it only makes sense if the name you choose is relevant to the calculation. "result" is pointless, it doesn't give useful information then you should just return. If you had a name that fits the context and the calculation itself isn't obvious, then its an easy and quick way to show what you are doing. – tdelaney Aug 19 '21 at 16:29
  • I would like to add that the method signature should be enough to tell what the return value should be. With that said, there is no need for an extracted return value. – Mustehssun Iqbal Aug 21 '21 at 16:12

2 Answers2

1

There is a reason to name variables (or a return value in your example) which is to inform future programmers of what you code is actually doing.

In the case of a return value, it could be (again with your example) that the function name describes the return value already, so no need to repeat that with a dedicated variable name.

I often use the Refactor/Introduce/Variable tool in PyCharm to create a variable to give it a name to explain what is happening.

quamrana
  • 37,849
  • 12
  • 53
  • 71
-1

If its about performence the second funtion will take less time by about 5%
But if you really want to do that you can

THW 10
  • 123
  • 7