Python in-memory cache with time to live

后端 未结 8 1531
后悔当初
后悔当初 2020-12-04 23:24

I have multiple threads running the same process that need to be able to to notify each other that something should not be worked on for the next n seconds its not the end o

8条回答
  •  死守一世寂寞
    2020-12-05 00:17

    Regarding an expiring in-memory cache, for general purpose use, a common design pattern to typically do this is not via a dictionary, but via a function or method decorator. A cache dictionary is managed behind the scenes. As such, this answer somewhat complements the answer by User which uses a dictionary rather than a decorator.

    The ttl_cache decorator in cachetools==3.1.0 works a lot like functools.lru_cache, but with a time to live.

    import cachetools.func
    
    @cachetools.func.ttl_cache(maxsize=128, ttl=10 * 60)
    def example_function(key):
        return get_expensively_computed_value(key)
    
    
    class ExampleClass:
        EXP = 2
    
        @classmethod
        @cachetools.func.ttl_cache()
        def example_classmethod(cls, i):
            return i * cls.EXP
    
        @staticmethod
        @cachetools.func.ttl_cache()
        def example_staticmethod(i):
            return i * 3
    

提交回复
热议问题