2012-06-25 18 views
1

在我的代碼中,我使用Python Decorator庫中的memoized類。需要memoized函數來像函數一樣詭異

我正在使用的一個庫對函數使用自省來獲取它所需的參數數量,並且在裝飾的函數上失敗。具體來說,它會檢查co_argcount變量。

if (PyInt_AsLong(co_argcount) < 1) { 
     PyErr_SetString(PyExc_TypeError, "This function has no parameters to mini\ 
mize."); 

看來argcount沒有被轉移到memoized函數。

>>> def f(x): 
...  return x 
... 
>>> f.func_code.co_argcount 
1 
>>> g = memoized(f) 
>>> g.func_code.co_argcount 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'memoized' object has no attribute 'func_code' 

如何修改memoized類,以便我的memoized函數看起來,味道和氣味像原來的功能?

回答

3

您需要創建一個簽名保留裝飾器。最簡單的方法是使用庫http://pypi.python.org/pypi/decorator,它負責爲您保留簽名。

該庫的內部相當醜陋(它使用exec!),但它封裝得很好。

0

它添加到您的memoized

def __getattr__(self, name): 
    if name.startswith('func_'): 
     return getattr(self.func, name) 
    raise AttributeError 

所以它會通過查找屬性爲func_...原來的功能。

也許你也會想寫一個__setattr__函數來拒絕寫這些屬性,但是如果你知道你不會嘗試改變這些值,那麼這是沒有必要的。