mardi 5 juin 2018

Pack return values

Let's say I have a dummy function which returns exactly what give as a parameter:

def dummy_single(arg1):
    """Repeat the same argument."""
    return arg1

I can use this function on the following way:

same_obj1 = dummy_single(obj1)

Now, if I want to allow this function to take several arguments, and return the same, I can pack and unpack the arguments:

def dummy_multiple(*args):
    """Repeat all given arguments."""
    return args

It works pretty well when called with multiple arguments:

same_obj1, same_obj2 = dummy_multiple(obj1, obj2)

However, this won't work as expected:

same_tuple = dummy_multiple(obj1)

same_obj1 contains a (packed) tuple, as opposed to the object in the two previous example. I thought about fixing this behavior on the following way, but it does not look clean as the returned type is different depending on the arguments.

def dummy_multiple_fixed(*args):
    """Repeat all given arguments."""
    if len(args) == 1:
        return args[0]
    return args

This is not a critical issue and is easily fixed. But I cannot find a clean and elegant way to fix this issue.

Aucun commentaire:

Enregistrer un commentaire