2014-10-27 31 views
2

我一直在使用python-aspectlib編織某個方面到某些方法 - 不幸的是這會將方法簽名更改爲Argspec(args=[], varargs='args', keywords='kwargs', default=None),這會在依賴於返回正確簽名的庫處理時產生問題。我可以在不更改方法/函數簽名的情況下使用python中的方面嗎?

有沒有辦法在不改變方法簽名的情況下使用python-aspectlib?如果沒有,有沒有其他的python方面庫可以做到這一點?

我看過裝飾模塊,它明確提到了更改方法簽名的問題:http://micheles.googlecode.com/hg/decorator/documentation.html#statement-of-the-problem,但我希望找到一個解決方案,我不需要修改我想編織的方法(因爲他們是第三方圖書館的一部分)。

我使用python 2.7.6

+1

如果'aspectlib'是一個開源庫;提交一個能夠保留函數簽名的補丁。相關:[你如何實現你的Python裝飾器是錯誤的](https://github.com/GrahamDumpleton/wrapt/tree/master/blog) – jfs 2014-10-27 13:16:15

+0

它看起來像Python 3.3之前,你必須使用'eval()'設置正確的函數簽名(正如'decorator'模塊所做的那樣)。在Python 3.3+中,'wrapper .__ signature__'被明確支持,[見PEP 362](http://legacy.python.org/dev/peps/pep-0362/)。 – jfs 2014-10-27 13:45:01

+1

當你需要自己實現時,這可能會有所幫助:http://stackoverflow.com/questions/23973783/python-decorator-with-arguments-of-decorated-function – User 2014-10-27 13:52:33

回答

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博客文章中提到的問題,但它充分填補了我最重要的標準:正確的方法簽名。

相關問題