Python检查调用函数时使用的输出参数的数量

2024-05-23 20:18:25 发布

您现在位置:Python中文网/ 问答频道 /正文

在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.

Tags: ofto对象nonenumberoutput参数return
2条回答

如果使用Python3,则可以在左侧使用extended iterable unpacking

>>> def f(n):
...    return tuple(range(n))
... 
>>> f(3)
(0, 1, 2)
>>> a,b,*c=f(20)
>>> a
0
>>> b
1
>>> c
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

使用您的函数,您可以执行以下操作:

^{pr2}$

在任何一种情况下,_将是Nonertr将是{}或{}

您可能希望从f显式返回一个元组,以避免以后出现歧义:

>>> def f(a,b=None):
...    return (1,2) if b else (1,)
... 
>>> rtr,*_=f(1),None
>>> rtr
(1,)
>>> rtr,*_=f(1,True),None
>>> rtr
(1,2)

如果您这样做,它也可以在Python 2X下工作:

Python 2.7:

>>> def f(a,b=None):
...    return (1,2) if b else (1,)
... 
>>> x,y=f(1),None
>>> x
(1,)
>>> x,y=f(1,True),None
>>> z
>>> x
(1, 2)

正如阿什维尼指出的那样,这似乎奏效了:

import inspect,dis

def expecting():
    """Return how many values the caller is expecting"""
    f = inspect.currentframe()
    f = f.f_back.f_back
    c = f.f_code
    i = f.f_lasti
    bytecode = c.co_code
    instruction = bytecode[i+3]
    if instruction == dis.opmap['UNPACK_SEQUENCE']:
        howmany = bytecode[i+4]
        return howmany
    elif instruction == dis.opmap['POP_TOP']:
        return 0
    return 1

def cleverfunc():
    howmany = expecting()
    if howmany == 0:
        print("return value discarded")
    if howmany == 2:
        return 1,2
    elif howmany == 3:
        return 1,2,3
    return 1

def test():
    cleverfunc()
    x = cleverfunc()
    print(x)
    x,y = cleverfunc()
    print(x,y)
    x,y,z = cleverfunc()
    print(x,y,z)

test()

相关问题 更多 >