我可以在python中使用方面而不更改方法/函数的签名吗?

2024-09-26 17:45:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

我使用的是python2.7.6


Tags: 模块方法nonedefault情况argsdecoratorkwargs
1条回答
网友
1楼 · 发布于 2024-09-26 17:45:09

我已经设法用以下代码“修复”了我的特定用例:

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博客文章中提到的所有问题,但它完全满足了对我来说最重要的标准:正确的方法签名。在

相关问题 更多 >

    热门问题