简体   繁体   English

从长度为1的元组中解包返回值

[英]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. 与前两个示例中的对象相反, same_obj1包含一个(打包的)元组。 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. 您不应该使用长度为1的元组作为特殊情况。 A function should have one well-defined return type. 一个函数应具有一个定义良好的返回类型。

Although, know that you can unpack a length-1 tuple: 虽然知道您可以解开长度为1的元组:

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

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

print(same_obj1) # 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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