Skip to content

Instantly share code, notes, and snippets.

@jnoller
Created March 3, 2011 20:54
Show Gist options
  • Save jnoller/853537 to your computer and use it in GitHub Desktop.
Save jnoller/853537 to your computer and use it in GitHub Desktop.
timedcache
from collections import namedtuple
from datetime import datetime, timedelta
timedvalue = namedtuple('TimedValue', 'expires value')
class ExpiredException(Exception):
pass
class TimedCache(dict):
def __getitem__(self, key):
""" Normal lookup, but checks to see if the item is expired, and if so,
raises an ExpiredException
"""
val = dict.__getitem__(self, key)
if val.expires and val.expires <= datetime.now():
raise ExpiredException()
return val.value
def __setitem__(self, packed, val):
""" Accepts (tuple(key, expiration), value), the tuple is unpacked and
used to set the key an expiration.
"""
key = packed # assume they're only doing x['k'] and not x['k','y']
expires = None
if isinstance(packed, tuple):
key, expires = packed
if expires: # assume they're (re)setting the timer.
expires = datetime.now() + timedelta(seconds=expires)
val = timedvalue(expires, val)
elif key in self:
val = timedvalue(dict.__getitem__(self, key).expires, val)
dict.__setitem__(self, key, val)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment