How do you disable caching when working with pythons functools? We have a boolean setting where you can disable the cache. This is for working locally.
I thought something like this:
@lru_cache(disable=settings.development_mode)
But there is no setting like that. Am I missing something? How are people doing this?
If you want to disable caching conditionally while using functools.lru_cache,
you need to manage this manually, You need a decorator that can conditionally apply lru_cache based on your settings
I am using the docs as the guide docsOnFunctools
Quotes from docs:
If maxsize is set to None, the LRU feature is disabled and the cache can grow without bound.If typed is set to true, function arguments of different types will be cached separately. If typed is false, the implementation will usually regard them as equivalent calls and only cache a single result. (Some types such as str and int may be cached separately even when typed is false.)
from functools import lru_cache, wraps
def remove_lru_cache(maxsize=128, typed=False, enable_cache=True):
def decorator(func):
if enable_cache:
return lru_cache(maxsize=maxsize, typed=typed)(func)
return func
return decorator
Then you can apply it to your code
# settings
your_settings = {
'dev_mode': True #set False to enable caching
}
@remove_lru_cache(maxsize=None, typed=False, enable_cache=not settings['dev_mode'])
def add(nums: List[int]) -> int:
return sum(nums)