Reputation: 418
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()
Upvotes: 15
Views: 13068
Reputation: 9621
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()
Upvotes: 7
Reputation: 39
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.
Upvotes: 0
Reputation: 16053
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 :P
Method 1 can be used for debug purposes or something else needs to be done before returning the value
Upvotes: 3
Reputation: 234875
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.
Upvotes: 6