如何找出函数的命名参数在 python 中

How do I figure out what the named arguments to a function are in python

我正在编写一个函数,它将采用要应用的函数字典作为其参数之一。所有这些函数至少有一个共同参数,但有些函数会有其他参数。在不失去让用户指定任意函数的灵活性(条件是它们的参数在范围内)的情况下,我如何内省一个函数以查看它的参数是什么?

这是一个虚拟示例:

def f1(x, y):
    return x+y

def f2(x):
    return x**2

fundict = dict(f1 = f1,
               f2 = f2)

y = 3 # this will always be defined in the same scope as fundict

for i in list(fundict.keys()):
    if <the args to the function have y in them>:
        fundict[i](x, y)
    else:
        fundict[i](x)

更好的做法是以编程方式查看函数的定义并将参数数组提供给它,条件是它们在范围内。

对于解决此问题的不同方法,我也很感激很好的一般性建议,这些方法可能不涉及自省函数。

您可以使用 inspect.getfullargspec.
示例:

>>> for k, fun in fundict.items():
...     print(fun.__name__, inspect.getfullargspec(fun)[0])
... 
f1 ['x', 'y']
f2 ['x']

您可以使用inspect.getfullargspec

import inspect

def f1(x, y):
    return x+y

def f2(x):
    return x**2

fundict = dict(f1 = f1,
               f2 = f2)

y = 3 # this will always be defined in the same scope as fundict

x = 1

for i in list(fundict.keys()):
    if 'y' in inspect.getfullargspec(fundict[i]).args:
        print(fundict[i](x, y))
    else:
        print(fundict[i](x))

这给出:

4
1