Tuesday, 15 February 2011

caching - Python LRU Cache Decorator Per Instance -



caching - Python LRU Cache Decorator Per Instance -

using lru cache decorator found here: http://code.activestate.com/recipes/578078-py26-and-py30-backport-of-python-33s-lru-cache/

from lru_cache import lru_cache class test: @lru_cache(maxsize=16) def cached_method(self, x): homecoming x + 5

i can create decorated class method ends creating global cache applies all instances of class test. however, intent create per instance cache. if instantiate 3 tests, have 3 lru caches rather 1 lru cache 3 instances.

the indication have happening when calling cache_info() on different class instances decorated methods, homecoming same cache statistics (which extremely unlikely occur given beingness interacted different arguments):

cacheinfo(hits=8379, misses=759, maxsize=128, currsize=128) cacheinfo(hits=8379, misses=759, maxsize=128, currsize=128) cacheinfo(hits=8379, misses=759, maxsize=128, currsize=128)

is there decorator or trick allow me cause decorator create cache each class instance?

assuming don't want modify code (e.g., because want able port 3.3 , utilize stdlib functools.lru_cache, or utilize functools32 out of pypi instead of copying , pasting recipe code), there's 1 obvious solution: create new decorated instance method each instance.

class test: def cached_method(self, x): homecoming x + 5 def __init__(self): self.cached_method = lru_cache(maxsize=16)(self.cached_method)

python caching decorator lru

No comments:

Post a Comment