[英]How can a decorator pass variables into a function without changing its signature?
[英]Can I use aspects in python without changing a method / function's signature?
我一直在使用python-aspectlib为某些方法编织一个方面-不幸的是,这将方法签名更改为Argspec(args=[], varargs='args', keywords='kwargs', default=None)
,这会产生问题当使用依赖inspect
库时,返回正确的签名。
有没有一种方法可以使用python-aspectlib而不更改方法的签名? 如果没有,还有其他的Python方面库可以做到这一点吗?
我查看了装饰器模块,该模块明确提到了更改方法签名的问题: http : //micheles.googlecode.com/hg/decorator/documentation.html#statement-of-the-problem ,但我希望找到不需要修改我要编织的方法的解决方案(因为它们是第三方库的一部分)。
我正在使用python 2.7.6
我已经通过以下代码针对特定用例成功解决了此问题:
from decorator import decorator
from Module1 import Class1
from Module2 import Class2
def _my_decorator(func, *args, **kwargs):
#add decorator code here
return func(*args, **kwargs)
def my_decorator(f):
return decorator(_my_decorator, f)
methods_to_decorate = [
'Class1.method1',
'Class2.method2',
]
for method in methods_to_decorate:
exec_str = method + '= my_decorator('+method+'.im_func)'
exec(exec_str)
这可能无法解决“ 如何实现Python装饰器是错误的”博客文章中提到的所有问题,但它完全满足了我最重要的条件:正确的方法签名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.