dgilland / cacheout

A caching library for Python

Home Page:https://cacheout.readthedocs.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

The in operator returns True after cache expiration

bzamecnik opened this issue · comments

After a cached expires (with finite ttl) the in operator still returns True (that the item is in the cache) until the get() method is called and corrects the internal state. It should be consistent with get() and return False right after expiration happens. Observed in the latest cachout==0.11.2.

It seems that the __contains__() method is not checking self.expired(key), in contrast to _get() which does. That would be the cause.

In addition there's a method has() which internally calls get() and checks expiration and distinguishes non-presence from None value. Does it mean that not checking expiration in __contains__ is intentional?

import cacheout
# works for all implementations (descendants) the Cache class
cache = cacheout.Cache(ttl=1)

Only calls to the in operator. After expiration it returns the wrong value.

cache.set('foo', 'bar')
for i in range(3):
    print('foo' in cache)
    time.sleep(1.5)

# True
# True # <-- wrong
# True # <-- wrong

Call the get() modifies the state and the in operator returns correct value afterwards.

cache.set('foo', 'bar') 
for i in range(3): 
    print('foo' in cache, cache.get('foo')) 
    time.sleep(1.5) 

# True bar
# True None # <-- wrong
# False None
cache.set('foo', 'bar') 
for i in range(3): 
    print(cache.get('foo'), 'foo' in cache)
    time.sleep(1.5) 

# bar True
# None False # OK
# None False

Thanks for reporting! Definitely a bug.

Fixed in 0.12.1.

Thank you for a very quick bug fix!