简体   繁体   中英

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).

Is there a way to use python-aspectlib without changing a method's signature? If not, are there other python aspect libraries that can do this?

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).

I'm using 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM