[英]Can I use aspects in python without changing a method / function's signature?
I've been using python-aspectlib to weave an aspect to certain methods - unfortunately this changes the methods signature to Argspec(args=[], varargs='args', keywords='kwargs', default=None)
, which creates problems when working with libraries that depend on inspect
returning the proper signature(s). 我一直在使用python-aspectlib为某些方法编织一个方面-不幸的是,这将方法签名更改为
Argspec(args=[], varargs='args', keywords='kwargs', default=None)
,这会产生问题当使用依赖inspect
库时,返回正确的签名。
Is there a way to use python-aspectlib without changing a method's signature? 有没有一种方法可以使用python-aspectlib而不更改方法的签名? If not, are there other python aspect libraries that can do this?
如果没有,还有其他的Python方面库可以做到这一点吗?
I've looked at the decorator module, which explicitly mentions the problem of changing a method signature: http://micheles.googlecode.com/hg/decorator/documentation.html#statement-of-the-problem , but I was hoping to find a solution where I don't need to modify the methods I want to weave (since they are part of a third party library). 我查看了装饰器模块,该模块明确提到了更改方法签名的问题: http : //micheles.googlecode.com/hg/decorator/documentation.html#statement-of-the-problem ,但我希望找到不需要修改我要编织的方法的解决方案(因为它们是第三方库的一部分)。
I'm using python 2.7.6 我正在使用python 2.7.6
I've managed to 'fix' this for my specific use case with the following piece of code: 我已经通过以下代码针对特定用例成功解决了此问题:
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)
This probably doesn't handle all of the issues mentioned in the How you implement your Python decorator is wrong blog posts, but it full fills the criteria most important to me: correct method signatures. 这可能无法解决“ 如何实现Python装饰器是错误的”博客文章中提到的所有问题,但它完全满足了我最重要的条件:正确的方法签名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.