Search code examples
pythonreturnrefactoringvariable-names

In python, is it best practice to always name your returned value?


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?


Solution

  • There is a reason to name variables (or a return value in your example) which is to inform future programmers of what your 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.