我想列出用于自记录REST API的方法的参数。我发现可以使用以下方法获取方法的参数:
method.__code__.co_varnames[:method.__code__.co_argcount]
但是,当装饰该方法时,这不起作用。
class Rator:
def __init__(self):
pass
def __call__(self, func):
def wrapper(instance, **kwargs):
func(instance, **kwargs)
return wrapper
class Klass:
def method(self, var_one=None, var_two=None):
pass
@Rator()
def decorated_method(self, var_one=None, var_two=None):
pass
if __name__ == '__main__':
klass = Klass()
print("method args is " + str(klass.method.__code__.co_varnames))
print("decorated method args is " + str(klass.decorated_method.__code__.co_varnames))
输出
method args is ('self', 'var_one', 'var_two')
decorated method args is ('instance',)
首选不需要更改装饰器的解决方案。
我知道这个问题是How to retrieve method arguments of a decorated python method的重复,但是很早以前就死了。
答案 0 :(得分:4)
您需要用functools.wraps包装装饰器,然后可以通过inspect.signature()检查方法:
import inspect
from functools import wraps
class Rator:
def __init__(self):
pass
def __call__(self, func, **kwargs):
@wraps(func)
def wrapper(instance):
func(instance, **kwargs)
return wrapper
class Klass:
def method(self, var_one=None, var_two=None):
pass
@Rator()
def decorated_method(self, argument1, var_one=None, var_two=None):
pass
if __name__ == '__main__':
klass = Klass()
print("method args is ", inspect.signature(klass.method))
print("decorated method args is ", inspect.signature(klass.decorated_method))
打印:
method args is (var_one=None, var_two=None)
decorated method args is (argument1, var_one=None, var_two=None)