我可以在不改变方法/功能签名的情况下使用python中的方面吗?

时间:2014-10-27 10:42:26

标签: python python-2.7 decorator aop

我一直在使用python-aspectlib为某些方法编织方面 - 遗憾的是,这会将方法签名更改为Argspec(args=[], varargs='args', keywords='kwargs', default=None),这会在使用依赖于inspect返回正确的库的库时产生问题签名(S)。

有没有办法在不更改方法签名的情况下使用python-aspectlib?如果没有,是否有其他python方面库可以做到这一点?

我看过装饰器模块,它明确提到了更改方法签名的问题:http://micheles.googlecode.com/hg/decorator/documentation.html#statement-of-the-problem,但我希望找到一个解决方案,我不需要修改我想要的方法编织(因为它们是第三方库的一部分)。

我正在使用python 2.7.6

1 个答案:

答案 0 :(得分:0)

我已经使用以下代码设法为我的特定用例“修复”了这个问题:

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)

这可能无法解决How you implement your Python decorator is wrong博文中提到的所有问题,但它完全符合我最重要的标准:正确的方法签名。