假设函数a_method的定义如下

def a_method(arg1, arg2):
    pass

从a_method本身开始,我怎么能得到参数名-例如,作为字符串的元组,如("arg1", "arg2")?


当前回答

在CPython中,参数的数量是

a_method.func_code.co_argcount

他们的名字在开头

a_method.func_code.co_varnames

这些是CPython的实现细节,所以这可能不适用于Python的其他实现,比如IronPython和Jython。

承认“传递”参数的一种可移植方法是使用func(*args, **kwargs)签名来定义函数。这在matplotlib中被大量使用,其中外层API层将大量关键字参数传递给底层API。

其他回答

在CPython中,参数的数量是

a_method.func_code.co_argcount

他们的名字在开头

a_method.func_code.co_varnames

这些是CPython的实现细节,所以这可能不适用于Python的其他实现,比如IronPython和Jython。

承认“传递”参数的一种可移植方法是使用func(*args, **kwargs)签名来定义函数。这在matplotlib中被大量使用,其中外层API层将大量关键字参数传递给底层API。

下面是另一种不使用任何模块获得函数参数的方法。

def get_parameters(func):
    keys = func.__code__.co_varnames[:func.__code__.co_argcount][::-1]
    sorter = {j: i for i, j in enumerate(keys[::-1])} 
    values = func.__defaults__[::-1]
    kwargs = {i: j for i, j in zip(keys, values)}
    sorted_args = tuple(
        sorted([i for i in keys if i not in kwargs], key=sorter.get)
    )
    sorted_kwargs = {
        i: kwargs[i] for i in sorted(kwargs.keys(), key=sorter.get)
    }   
    return sorted_args, sorted_kwargs


def f(a, b, c="hello", d="world"): var = a
    

print(get_parameters(f))

输出:

(('a', 'b'), {'c': 'hello', 'd': 'world'})

我在谷歌上搜索如何打印函数名,并为赋值提供参数,我必须创建一个装饰器来打印它们,我使用了这个:

def print_func_name_and_args(func):
    
    def wrapper(*args, **kwargs):
    print(f"Function name: '{func.__name__}' supplied args: '{args}'")
    func(args[0], args[1], args[2])
    return wrapper


@print_func_name_and_args
def my_function(n1, n2, n3):
    print(n1 * n2 * n3)
    
my_function(1, 2, 3)

#Function name: 'my_function' supplied args: '(1, 2, 3)'

是否可以使用inspect API从下面的代码中的lambda func fun读取常量参数值-1 ?

def my_func(v, axis):
  pass

fun = lambda v: my_func(v, axis=-1)

布莱恩的回答更新如下:

如果Python 3中的函数只有关键字参数,那么你需要使用inspect.getfullargspec:

def yay(a, b=10, *, c=20, d=30):
    pass
inspect.getfullargspec(yay)

收益率:

FullArgSpec(args=['a', 'b'], varargs=None, varkw=None, defaults=(10,), kwonlyargs=['c', 'd'], kwonlydefaults={'c': 20, 'd': 30}, annotations={})