Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple return values in python

Tags:

python

I want to change a python function to return two values. How do I achieve that without affecting any of the previous function calls which only expect one return value?

For eg.

Original Definition:

def foo():
    x = 2
    y = 2
    return (x+y)

sum = foo()

Ne Definition:

def foo():
    x = 2
    y = 2
   return (x+y), (x-y)

sum, diff = foo()

I want to do this in a way that the previous call to foo also remains valid? Is this possible?

like image 687
Sharvari Marathe Avatar asked Jul 30 '12 17:07

Sharvari Marathe


People also ask

Can you have multiple return values in Python?

You can return multiple values from a function in Python. To do so, return a data structure that contains multiple values, like a list containing the number of miles to run each week. Data structures in Python are used to store collections of data, which can be returned from functions.

Can you have multiple return values?

You can return multiple values from a function using either a dictionary, a tuple, or a list. These data types all let you store multiple values.

How can I return multiple values from a function?

We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data.


2 Answers

def foo(return_2nd=False):

    x = 2
    y = 2
    return (x+y) if not return_2nd else (x+y),(x-y)

then call new version

sum, diff = foo(True)
sum = foo() #old calls still just get sum
like image 141
Joran Beasley Avatar answered Oct 09 '22 10:10

Joran Beasley


By changing the type of return value you are changing the "contract" between this function and any code that calls it. So you probably should change the code that calls it.

However, you could add an optional argument that when set will return the new type. Such a change would preserve the old contract and allow you to have a new one as well. Although it is weird having different kinds of return types. At that point it would probably be cleaner to just create a new function entirely, or fix the calling code as well.

like image 36
Justin Ethier Avatar answered Oct 09 '22 09:10

Justin Ethier