简体   繁体   English

我如何找出函数的命名参数在python中是什么

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

I am writing a function that is going to take, as one of it's arguments, a dictionary of functions to apply.我正在编写一个函数,它将把要应用的函数字典作为参数之一。 All of these functions will have at least one argument in common, but some will have others.所有这些函数都至少有一个共同的参数,但有些函数会有其他参数。 Without losing the flexibility of letting the user specify arbitrary functions (conditional on having their arguments in scope), how can I introspect a function to see what its arguments are?在不失去让用户指定任意函数的灵活性的情况下(以它们的参数在范围内为条件),我如何内省一个函数以查看它的参数是什么?

Here's a dummy example:这是一个虚拟示例:

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)

Even better would be something that programmatically looks at the definition of the function and feeds the array of arguments to it, conditional on them being in-scope.更好的是以编程方式查看函数的定义并将参数数组提供给它,条件是它们在范围内。

I'd also appreciate good general suggestions for different ways to go about solving this problem, that might not involve introspecting a function.我也很欣赏有关解决此问题的不同方法的一般性建议,这可能不涉及内省函数。

You can use inspect.getfullargspec你可以使用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))

This gives:这给出:

4
1

You can use inspect.getfullargspec .您可以使用inspect.getfullargspec
Example:例子:

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

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

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