Search code examples
pythonpep8

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


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()

Solution

  • 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()