【问题标题】:Can I use aspects in python without changing a method / function's signature?我可以在不更改方法/函数签名的情况下在 python 中使用方面吗?
【发布时间】:2014-12-22 12:34:42
【问题描述】:

我一直在使用 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

【问题讨论】:

  • 如果aspectlib 是一个开源库;提交一个可以保留函数签名的补丁。相关:How you implemented your Python decorator is wrong
  • 在 Python 3.3 之前,您必须使用 eval() 来设置正确的函数签名(就像 decorator 模块所做的那样)。在 Python 3.3+ 中,wrapper.__signature__ 被明确支持,see PEP 362
  • 当您需要自己实现时,这可能会有所帮助:stackoverflow.com/questions/23973783/…
  • aspectlib 是一个开源库 - 不幸的是,我的 Python 知识(还)还不足以理解他们在做什么(或实际修补它)。感谢您的链接,它们非常有帮助。

标签: python python-2.7 decorator aop


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-08-20
    • 1970-01-01
    • 2011-06-10
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 2018-10-09
    • 2017-07-28
    相关资源
    最近更新 更多