假设函数a_method的定义如下

def a_method(arg1, arg2):
    pass

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


当前回答

这里有一些东西,我认为会为你想要的工作,使用装饰。

class LogWrappedFunction(object):
    def __init__(self, function):
        self.function = function

    def logAndCall(self, *arguments, **namedArguments):
        print "Calling %s with arguments %s and named arguments %s" %\
                      (self.function.func_name, arguments, namedArguments)
        self.function.__call__(*arguments, **namedArguments)

def logwrap(function):
    return LogWrappedFunction(function).logAndCall

@logwrap
def doSomething(spam, eggs, foo, bar):
    print "Doing something totally awesome with %s and %s." % (spam, eggs)


doSomething("beans","rice", foo="wiggity", bar="wack")

运行它,它将产生以下输出:

C:\scripts>python decoratorExample.py
Calling doSomething with arguments ('beans', 'rice') and named arguments {'foo':
 'wiggity', 'bar': 'wack'}
Doing something totally awesome with beans and rice.

其他回答

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

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'})

现在dir()和vars()呢?

似乎做什么是被要求超级简单…

必须从函数范围内调用。

但要注意,它将返回所有局部变量,所以如果需要,请确保在函数的最开始执行。

还要注意,正如评论中指出的那样,这不允许从作用域之外执行此操作。所以不完全是OP的情况,但仍然符合题目。这就是我的回答。

为了更新一点Brian的答案,现在有一个很好的后端口inspect。可以在较旧的python版本中使用的签名:funcsigs。 所以我的个人偏好是

try:  # python 3.3+
    from inspect import signature
except ImportError:
    from funcsigs import signature

def aMethod(arg1, arg2):
    pass

sig = signature(aMethod)
print(sig)

为了好玩,如果你有兴趣玩签名对象,甚至动态地创建随机签名的函数,你可以看看我的makefun项目。

检查。签名很慢。最快的方法是

def f(a, b=1, *args, c, d=1, **kwargs):
   pass

f_code = f.__code__
f_code.co_varnames[:f_code.co_argcount + f_code.co_kwonlyargcount]  # ('a', 'b', 'c', 'd')

我觉得你要找的是当地人的方法


In [6]: def test(a, b):print locals()
   ...: 

In [7]: test(1,2)              
{'a': 1, 'b': 2}