给定 Python 函数:
def a_method(arg1, arg2):
pass
如何提取参数的数量和名称。即,鉴于我有对 func
的引用,我希望 func.[something]
返回 ("arg1", "arg2")
.
这个使用场景是我有一个装饰器,我希望使用方法参数的顺序与它们作为键出现在实际函数中的顺序相同。即,当我调用 a_method("a", "b")
时,打印 "a,b"
的装饰器看起来如何?
最佳答案
看看inspect
模块 - 这将为您检查各种代码对象属性。
>>> inspect.getfullargspec(a_method)
(['arg1', 'arg2'], None, None, None)
其他结果是 *args 和 **kwargs 变量的名称,以及提供的默认值。即。
>>> def foo(a, b, c=4, *arglist, **keywords): pass
>>> inspect.getfullargspec(foo)
(['a', 'b', 'c'], 'arglist', 'keywords', (4,))
请注意,某些可调用对象在某些 Python 实现中可能是不可自省(introspection)的。例如,在 CPython 中,C 中定义的一些内置函数不提供有关其参数的元数据。因此,如果您在内置函数上使用 inspect.getfullargspec()
,您将得到一个 ValueError
。
从 Python 3.3 开始,您可以使用 inspect.signature()
查看可调用对象的调用签名:
>>> inspect.signature(foo)
<Signature (a, b, c=4, *arglist, **keywords)>
https://stackoverflow.com/questions/218616/