Created
March 3, 2011 20:54
-
-
Save jnoller/853537 to your computer and use it in GitHub Desktop.
timedcache
This file contains 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
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