简体   繁体   中英

Unpack return value from length-1 tuple

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

Please note that this function happens to be the identity, but this is not the core of the problem. You can imagine any function returning a variable-length tuple.

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.

You should not make a special case out of the length-1 tuple. A function should have one well-defined return type.

Although, know that you can unpack a length-1 tuple:

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

same_obj1, = dummy_multiple(1)
#        ^ notice the comma here

print(same_obj1) # 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM