假设函数a_method的定义如下
def a_method(arg1, arg2):
pass
从a_method本身开始,我怎么能得到参数名-例如,作为字符串的元组,如("arg1", "arg2")?
假设函数a_method的定义如下
def a_method(arg1, arg2):
pass
从a_method本身开始,我怎么能得到参数名-例如,作为字符串的元组,如("arg1", "arg2")?
当前回答
检查。签名很慢。最快的方法是
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')
其他回答
看一下inspect模块——它将为你检查各种代码对象属性。
>>> inspect.getfullargspec(a_method)
(['arg1', 'arg2'], None, None, None)
其他结果是*args和**kwargs变量的名称,以及提供的默认值。ie。
>>> def foo(a, b, c=4, *arglist, **keywords): pass
>>> inspect.getfullargspec(foo)
(['a', 'b', 'c'], 'arglist', 'keywords', (4,))
注意,在Python的某些实现中,一些可调用对象可能不是可内省的。例如,在CPython中,一些用C定义的内置函数不提供关于其参数的元数据。因此,如果在内置函数上使用inspect.getfullargspec(),将会得到一个ValueError。
从Python 3.3开始,你可以使用inspect.signature()来查看可调用对象的调用签名:
>>> inspect.signature(foo)
<Signature (a, b, c=4, *arglist, **keywords)>
返回参数名列表,负责部分和正则函数:
def get_func_args(f):
if hasattr(f, 'args'):
return f.args
else:
return list(inspect.signature(f).parameters)
我觉得你要找的是当地人的方法
In [6]: def test(a, b):print locals()
...:
In [7]: test(1,2)
{'a': 1, 'b': 2}
为了更新一点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项目。
这里有一些东西,我认为会为你想要的工作,使用装饰。
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.