在python中有没有一种方法可以从被调用函数内部检查调用函数的输出参数的数量?在
例如:
a,b = Fun() #-> number of output arguments would be 2
a,b,c = Fun() #-> number of output arguments would be 3
在matlab中,这将使用nargout 我知道这样做的"normal way"是将不需要的值解压到变量中:
^{pr2}$我要做的很简单。我有一个函数,如果用某些参数调用,它将返回一个对象,否则将返回两个对象:
def f(a,b=None):
if b is None:
return 1
else:
return 1,2
但我想强制元组解包不要发生,并强制错误,例如:
x = f(a) #-> Fine
x,y = f(a,b) #-> Fine
x,y = f(a) #-> Will throw native error: ValueError: need more than Foo values to unpack
x = f(a,b) #-> Want to force this to throw an error and not default to the situation where x will be a tuple.
如果使用Python3,则可以在左侧使用extended iterable unpacking:
使用您的函数,您可以执行以下操作:
^{pr2}$在任何一种情况下,}或{}
_
将是None
,rtr
将是{您可能希望从f显式返回一个元组,以避免以后出现歧义:
如果您这样做,它也可以在Python 2X下工作:
Python 2.7:
正如阿什维尼指出的那样,这似乎奏效了:
相关问题 更多 >
编程相关推荐