Search code examples
pythoncaching

Python Cachetools unless


I am learning how to use caching in python for the first time. I'm trying out cachetools and have run into an issue. I got caching to work fine using the below annotation above my method. Does cachetools have an "unless" function? So it will cache unless some variable is false after code is executed. Currently it caches every time no matter what. I have searched and am not able to find an answer.

@cached(cache=TTLCache(maxSize=64, ttl=300)
Def retrieveValues(input)
    Return 'testValue'

But is it possible for something like:

@cached(cache=TTLCache(maxSize=64, ttl=300, unless="myValue")
Def retrieveValues(input)
    #don't cache in this situation
    MyValue=False
    return 'testValue'

Solution

  • The short answer is no. But you can work around it. If you don't want the answer you got, then throw an exception. This will cause the cache not to save the returned value, since there is no return value.

    You will have to have an enclosing function catch the exception, and deal with it however you want.