Does PEP8 suggest returning a variable or a function call from a method?

Question:

What is the recommended way for returning values from a method and why, according to PEP8? I tried finding documentation on this in PEP8, but couldn’t find anything.

Method 1

def method():
    a = meth2()
    return a

Method 2

def method():
    return meth2()
Asked By: firekhaya

||

Answers:

Normally I plump for Method 1, particularly in mathematical code.

Method 1 is easier to debug and therefore maintain, since you can put a breakpoint on return a, and see easily what a is. (Wonderful as they are, the C++ Boost programmers like to adopt Method 2 with very large call stacks which can make debugging very difficult – you have to resort to inspecting a CPU register!)

Good python interpreters will have named return value optimisation, so you ought not worry about an unnecessary value copy being taken.

Answered By: Bathsheba

Method 2 seems good because there isn’t any need of a variable if you are just returning the value received from the function. Plus, it looks good this way 😛

Method 1 can be used for debug purposes or something else needs to be done before returning the value

Answered By: Pankaj Singhal

PEP8 doesn’t specify whether or not you should return a variable versus a function.

However, it does say that you should be consistent:

Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None , and an explicit return statement should be present at the end of the function (if reachable).

# Yes
def myfunction(a: int, b: int) -> int:
    if a % 2 == 0:
        return int(a ** b)
    else:
        return 0

# No
def my_bad_function(a: int, b: int) -> int:
    if a % 2 == 0:
        return int(a ** b)
    # Implicitly returns None when the above if statement evaluates False

It’s also a good idea (although not covered in PEP8) to return variables of the same type.
You’ll see that I added optional type hints in the above functions. The second function will occasionally return None.
This may cause issues if another block of code which uses this function expects the return value to have the same attributes as int, such as int.bit_length()

Example of code that would result in an exception:

for n in range(1, 10):
    nlen = my_bad_function(n * 5, n).bit_length()
Answered By: Vasili Syrakis

I prefer method 1 bcos it makes debugging easy (can you live without it?)

If I am debugging code which is mehtod 2 then I use pycharm Evaluate Expression option to know what return statement is returning.

Answered By: shoaib shaikh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.