簡體   English   中英

我可以在不更改方法/函數簽名的情況下在python中使用方面嗎?

[英]Can I use aspects in python without changing a method / function's signature?

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

我已經通過以下代碼針對特定用例成功解決了此問題:

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)

這可能無法解決“ 如何實現Python裝飾器是錯誤的”博客文章中提到的所有問題,但它完全滿足了我最重要的條件:正確的方法簽名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM