Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a variable vs return a function call

Tags:

python

pep8

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()
like image 637
firekhaya Avatar asked Jan 13 '17 09:01

firekhaya


People also ask

Is return a function call?

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.

What happens when you return a function call?

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.

What is difference between function and return function?

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.

How do you return a variable from a function?

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.


2 Answers

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

like image 57
Pankaj Singhal Avatar answered Sep 28 '22 08:09

Pankaj Singhal


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.

like image 22
Bathsheba Avatar answered Sep 28 '22 06:09

Bathsheba