【发布时间】:2011-06-23 01:49:15
【问题描述】:
我想要的是一个 memoization 装饰器:
- 可以使用参数和关键字参数来记忆实例方法
- 有一个可以通过一次调用(全局)清除的缓存(与使用每个函数缓存的这个相比:python resettable instance method memoization decorator)
- 相当有效
我已经调整了我看到的一个示例并提出了以下内容:
import functools
class Memoized(object):
"""Decorator that caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned, and
not re-evaluated.
"""
__cache = {}
def __init__(self, func):
self.func = func
self.key = (func.__module__, func.__name__)
def __call__(self, *args):
try:
return Memoized.__cache[self.key][args]
except KeyError:
value = self.func(*args)
Memoized.__cache[self.key] = {args : value}
return value
except TypeError:
# uncachable -- for instance, passing a list as an argument.
# Better to not cache than to blow up entirely.
return self.func(*args)
def __get__(self, obj, objtype):
"""Support instance methods."""
return functools.partial(self.__call__, obj)
@staticmethod
def reset():
Memoized.__cache = {}
我的问题是缓存部分似乎涉及很多开销(例如,对于递归函数)。以下面的函数为例,我可以在非记忆版本比记忆版本更短的时间内调用 fib(30) 十次。
def fib(n):
if n in (0, 1):
return n
return fib(n-1) + fib(n-2)
谁能推荐一个更好的方法来编写这个装饰器? (或者给我一个更好(即更快)的装饰器来做我想要的)。 我对保留方法签名或帮助自省工具“了解”装饰函数的任何内容不感兴趣。
谢谢。
附:使用python 2.7
【问题讨论】:
标签: python memoization