假设函数a_method的定义如下
def a_method(arg1, arg2):
pass
从a_method本身开始,我怎么能得到参数名-例如,作为字符串的元组,如("arg1", "arg2")?
假设函数a_method的定义如下
def a_method(arg1, arg2):
pass
从a_method本身开始,我怎么能得到参数名-例如,作为字符串的元组,如("arg1", "arg2")?
当前回答
在decorator方法中,你可以这样列出原始方法的参数:
import inspect, itertools
def my_decorator():
def decorator(f):
def wrapper(*args, **kwargs):
# if you want arguments names as a list:
args_name = inspect.getargspec(f)[0]
print(args_name)
# if you want names and values as a dictionary:
args_dict = dict(itertools.izip(args_name, args))
print(args_dict)
# if you want values as a list:
args_values = args_dict.values()
print(args_values)
如果**狼对你来说很重要,那就有点复杂了:
def wrapper(*args, **kwargs):
args_name = list(OrderedDict.fromkeys(inspect.getargspec(f)[0] + kwargs.keys()))
args_dict = OrderedDict(list(itertools.izip(args_name, args)) + list(kwargs.iteritems()))
args_values = args_dict.values()
例子:
@my_decorator()
def my_function(x, y, z=3):
pass
my_function(1, y=2, z=3, w=0)
# prints:
# ['x', 'y', 'z', 'w']
# {'y': 2, 'x': 1, 'z': 3, 'w': 0}
# [1, 2, 3, 0]
其他回答
在CPython中,参数的数量是
a_method.func_code.co_argcount
他们的名字在开头
a_method.func_code.co_varnames
这些是CPython的实现细节,所以这可能不适用于Python的其他实现,比如IronPython和Jython。
承认“传递”参数的一种可移植方法是使用func(*args, **kwargs)签名来定义函数。这在matplotlib中被大量使用,其中外层API层将大量关键字参数传递给底层API。
在Python 3中。+有了Signature对象,获得参数名到值之间映射的简单方法就是使用Signature的bind()方法!
例如,这是一个用于打印地图的装饰器:
import inspect
def decorator(f):
def wrapper(*args, **kwargs):
bound_args = inspect.signature(f).bind(*args, **kwargs)
bound_args.apply_defaults()
print(dict(bound_args.arguments))
return f(*args, **kwargs)
return wrapper
@decorator
def foo(x, y, param_with_default="bars", **kwargs):
pass
foo(1, 2, extra="baz")
# This will print: {'kwargs': {'extra': 'baz'}, 'param_with_default': 'bars', 'y': 2, 'x': 1}
看一下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)>
这里有一些东西,我认为会为你想要的工作,使用装饰。
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'})