What is the recommended Pythonic way for returning values from a method and why? Is there any documentation on this in the PEP8 style guide, I couldn't find any.
Method 1
def method():
a = meth2()
return a
Method 2
def method():
return meth2()
A return is a value that a function returns to the calling script or function when it completes its task. A return value can be any one of the four variable types: handle, integer, object, or string. The type of value your function returns depends largely on the task it performs.
A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function. For more information, see Return type.
A function is something whic take parameters and do some calculations and operations and returns value. Now your question is what are they Function: It is simply a set of various processes Return value: It is final result after all calculations are done. Which is returned by function from where it is called.
To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With