Reputation: 79
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?
Upvotes: 5
Views: 1512
Reputation: 134167
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.
Upvotes: 2
Reputation: 113930
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
Upvotes: 12
Reputation: 8837
I'm sorry to tell you, but function overloading is not valid in Python. Because Python does not do type-enforcement, multiple definitions of foo results in the last valid one being used. One common solution is to define multiple functions, or to add a parameter in the function as a flag (which you would need to implement yourself)
Upvotes: 0