Python的LRU缓存的操作

时间:2016-08-29 16:38:44

标签: python python-3.x

我有以下代码:

def sharpe(self):
    return (self.weighted_returns()/self.weighted_returns().std())*np.sqrt(252)

self.weighted_returns()有一个@lru_cache(maxsize=None)装饰者。

self.weighted_returns()会计算一次还是两次?

1 个答案:

答案 0 :(得分:0)

您可以使用functools.lru_cache。但是如果你只是缓存self的计算而且函数没有使用参数,那就太过分了。

相反,我从金字塔中窃取了懒惰的reify装饰者:

class reify(object):
    def __init__(self, wrapped):
        self.wrapped = wrapped
        update_wrapper(self, wrapped)

    def __get__(self, inst, objtype=None):
        if inst is None:
            return self
        val = self.wrapped(inst)
        setattr(inst, self.wrapped.__name__, val)
        return val

并在weighted_returns上使用它,将其转换为延迟计算的属性:

@reify
def weighted_returns(self):
    # calculate the returns using self normally
    return returns

然后你的计算将是

self.weighted_returns / self.weighted_returns.std() * np.sqrt(252)

(注意缺少括号)。

functools.lru_cache(maxsize=None)不同,它会保留一个无限大小的字典(在你杀死程序之前它的大小会增加),reify装饰器会将计算结果缓存在实例本身上。如果实例是垃圾收集的,那么它的缓存加权返回也是如此。