Last active
December 18, 2015 12:59
-
-
Save sgk/5787193 to your computer and use it in GitHub Desktop.
Simple cache: dictionary with expire
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#vim:set fileencoding=utf-8 | |
import time | |
# Cache with Expire | |
class Cache: | |
def __init__(self, timeout): | |
# Actual expire is more than timeout and less than timeout*3. | |
self.timeout_ = timeout | |
self.clear() | |
def clear(self): | |
self.old_ = {} | |
self.current_ = {} | |
self.limit_ = 0 | |
def __len__(self): | |
return len(self.old_) + len(self.current_) | |
def __setitem__(self, key, value): | |
self.housekeep() | |
self.current_[key] = value | |
# Don't care even if old_ has the key. | |
def __getitem__(self, key): | |
# KeyError raised if key is not found. | |
self.housekeep() | |
try: | |
return self.current_[key] | |
except KeyError: | |
return self.old_[key] | |
def housekeep(self): | |
now = time.time() | |
if now > self.limit_: | |
if now > self.limit_ + self.timeout_: | |
self.old_ = {} | |
else: | |
self.old_ = self.current_ | |
self.current_ = {} | |
self.limit_ = now + self.timeout_ | |
class AccurateCache(Cache): | |
def __init__(self, timeout): | |
Cache.__init__(self, timeout) | |
def __setitem__(self, key, value): | |
Cache.__setitem__(self, key, (value, time.time())) | |
def __getitem__(self, key): | |
value, added = Cache.__getitem__(self, key) | |
if time.time() > added + self.timeout_: | |
raise KeyError | |
return value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment