Python LRU Cache Decorator Per Instance

前端 未结 3 1448
情书的邮戳
情书的邮戳 2020-12-13 09:16

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

from lru_cache import lr         


        
3条回答
  •  囚心锁ツ
    2020-12-13 09:25

    Assuming you don't want to modify the code (e.g., because you want to be able to just port to 3.3 and use the stdlib functools.lru_cache, or use functools32 out of PyPI instead of copying and pasting a recipe into your code), there's one obvious solution: Create a new decorated instance method with each instance.

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

提交回复
热议问题