[SOLVED] How to increase return values of functions without breaking legacy code?


For example lets say you have a function:

def foo(a): 
    return a

And there’s heaps of legacy code which uses this function:

amount = 4 + foo(a)

What if I need to increase the return values of foo without breaking existing code:

def foo(a)
   return a, a + 5

Now when I do this, variable ‘amount’ is not the correct answer, because a is now, in pylint’s words ‘a tuple’ so amount will change from returning a + 4, to returning (a, a+5) + 4

how do I add ‘a + 5’ to foo, while still allowing amount to be a single scalar value, rather than a tuple?


Perhaps something like this would work:

def foo(a, new_usage=False):
    if not new_usage:
        return a

    return a + 5

Then call your function like this for all new usage situations:

foo(a, True)

For example, your old code would still work:

In [40]: amount = 4 + foo(4)

In [41]: amount
Out[41]: 8

And for new usage, you could do this:

In [42]: amount = 4 + foo(4, True)

In [43]: amount
Out[43]: 13

Answered By – Ashish Acharya

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *