Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python Cachetools can items have different ttl?

Im using @cachetools.func.ttl_cache(maxsize=3, ttl=3600, timer=time.time, typed=False) to cache different data frames. The function being wrapped doesn't build the DF itself, but given an argument calls the right function.

Depending on the argument the DF may be time consuming or fast to build, given that I want to modify the item ttl (time-to-live). So that item 1 may have ttl=3600 while item 2 ttl=10800.

Is that functionality supported? using a global variable or any other way? docs

like image 966
Carlos P Ceballos Avatar asked Dec 22 '25 21:12

Carlos P Ceballos


1 Answers

Will is most likely correct, but just in case you want to try, I think subclass TTLCache and overwrite one function should work:

from cachetools import Cache, TTLCache

cache = TTLItemCache(maxsize=2, ttl=100)
# ttl=100
cache.__setitem__('key1', 'val1')
# ttl=200
cache.__setitem__('key2', 'val2', ttl=200)

class TTLItemCache(TTLCache):
    def __setitem__(self, key, value, cache_setitem=Cache.__setitem__, ttl=None):
        super(TTLItemCache, self).__setitem__(key, value)
        if ttl:
            link = self._TTLCache__links.get(key, None)
            if link:
                link.expire += ttl - self.ttl
like image 117
vlad Avatar answered Dec 24 '25 10:12

vlad