pythonpython-3.xcaching

getting `cache_info()` with cachetools


I'm using cachetools and I want to get the cache_info():

class UserData(object):
    def __init__():
        ...

    @cached(cache=TTLCache(maxsize=1024, ttl=600))
    def get_user_data(self, user_id):
        return self.redis.get_user_data(user_id)

    def get_cache_info():
        return self.get_user_data.cache_info()

I want to get the cache statistics as appear in this answer:

>>> foo.cache_info()
CacheInfo(hits=1, misses=1, maxsize=5, currsize=1)

I know that's a different cache (I'm using 3rd party library) but in the documentation above the cache_info does exist. Is there a way to get the TTLCache statistics somehow?


Solution

  • By the code and documentation you should use ttl_cache from func.py:

    from cachetools.func import ttl_cache
    
    
    class UserData(object):
        ...
        @ttl_cache(maxsize=1024, ttl=600)
        def get_user_data(self, user_id):
            return self.redis.get_user_data(user_id)
    

    You should then be able to call UserData.get_user_data.cache_info().

    cached decorator does not maintain any statistics.