Skip to content

Instantly share code, notes, and snippets.

@sgk
Last active December 18, 2015 12:59
Show Gist options
  • Save sgk/5787193 to your computer and use it in GitHub Desktop.
Save sgk/5787193 to your computer and use it in GitHub Desktop.
Simple cache: dictionary with expire
#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