5

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?

3 Answers 3

12
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
Sign up to request clarification or add additional context in comments.

4 Comments

Nice hack. If you wanted to go all Java on things here, couldn't you change it to return a custom class that acts like an int (the first value normally), but could also be indexed like a tuple? Then you don't even need to change the calling signature.
you could but that would be more work I think ... this was the simplest way(it seemed to me) to accomplish what the OP wanted...
@PauloScardine nope. at least not that I know of ...although he does vaguely resemble me
I highly recommend to call the function foo this way: foo(return_2nd=True) instead of foo(True) because is more explicit, enhances readability and will be clear to other programers that don't know that this function can return different number of results depenting on the parameter. Of course return_2nd can be changed to something more explicit like return_diff or something like that.
2

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.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.