Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return multiple values in python without breaking previous code

I had a version 1 of a function like:

def f(a,b,c):
    #Some processing
    return some_result

Later, I upgraded it to version 2.

def f(a,b,c):
    #Some processing
    #Some more processing
    return some_result, additional_result

The latter version returns a tuple. Hence all client code using version 1 gets obsolete. Can I get additional_result on demand?

That is you get additional_result only when you ask for it while you continue to get some_result as if nothing changed.

One trick I thought of:

def f(a,b,c, need_additional = False):
    #Some processing
    #Some more processing
    if not need_addional:
        return some_result
    else:
        return some_result, additional_result

Anything better? Or more generic?

like image 812
jerrymouse Avatar asked Dec 04 '22 04:12

jerrymouse


1 Answers

I think a more elegant solution would be to make your old function a legacy wrapper for your new function:

def f(a,b,c):
    some_result, additional_result = f_new(a,b,c)
    return some_result

def f_new(a,b,c):
    #Some processing
    #Some more processing
    return some_result, additional_result

I have to admit I mostly use the pattern you've suggested and not mine :), but default arguments for backwards compatibility are not that great of a practice.

like image 62
Not_a_Golfer Avatar answered Dec 05 '22 18:12

Not_a_Golfer