Search code examples
pythonparadigms

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?


Solution

  • I am finally implementing it like:

    def f(a,b,c, v2 = False):
        #Some processing
        #Some more processing
        if not v2:
            return some_result
        else:
            v2_dict = {}
            v2_dict['additional_result'] = additional_result
            v2_dict['...'] = ...
            return some_result, v2_dict
    

    Advantages:

    • Legacy code doesn't break.
    • No limitation on return values in future edition.
    • Code is manageable.