How to bypass a function with @functools.lru_cache decorator

Viewed 474

Hope you are doing well!

I'm using a function that is utilizing the lru_cache of functools library. for example:

@functools.lru_cache(maxsize=pow(2,13))
def get_id(word):
    # retrieving id, using cache if possible

I would like on some occasions to bypass the cache, thus getting the ID straight from the source, but I wouldn't like to create 2 separate functions (one with cache, and the other without) that are running exactly the same code. Reading the documentation of functools on docs.python I understand that the cache can be bypassed:

The original underlying function is accessible through the wrapped attribute. This is useful for introspection, for bypassing the cache, or for rewrapping the function with a different cache.

I've tried doing so with a wrapper function, but since the inner function exists only while the outer function was running, the cache was reset on every call.

I would appreciate any help on the matter.

1 Answers

what the documentation is telling you is that you can access the wrapped function directly this way (bypassing the caching):

get_id.__wrapped__(word="hello")

you could add one additional layer with a flag:

from functools import lru_cache

@lru_cache(maxsize=pow(2, 13))
def get_cached(word):
    return get_raw(word)

def get_raw(word):
    # your logic goes here...
    pass

def get_id(word, cached=True):
    if cached:
        return get_cached(word)
    else:
        return get_raw(word)
Related