Skip to content

Instantly share code, notes, and snippets.

@EnigmaCurry
Created March 3, 2011 18:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EnigmaCurry/853227 to your computer and use it in GitHub Desktop.
Save EnigmaCurry/853227 to your computer and use it in GitHub Desktop.
@jessenoller lunch break challenge : http://twitter.com/#!/jessenoller/status/43371023306981376
from threading import Timer
class SuicidalKey(object):
"""
>>> k = SuicidalKey("asdf",30)
>>> k.key
'asdf'
>>> # Before 30 seconds are up
>>> k.reset_expiration(30)
>>> # Wait 30 seconds
>>> k.key
None
"""
def __init__(self, key, expiration_time=300):
self.key = key
self.__expire_timer = Timer(0,None)
self.reset_expiration(expiration_time)
def __expire_key(self):
self.key = None
def reset_expiration(self, expiration_time=300):
if self.key:
self.__expire_timer.cancel()
self.__expire_timer = Timer(expiration_time, self.__expire_key)
self.__expire_timer.start()
@zzzeek
Copy link

zzzeek commented Mar 3, 2011

import time

class Value(object):
    def __init__(self, value):
        self.value = value
        self.timestamp = time.time()

class ExpireDict(dict):
    def __init__(self, expire_time):
        self.expire_time = expire_time

    def __setitem__(self, key, value):
        dict.__setitem__(self, key, Value(value))

    def __getitem__(self, key):
        val = dict.__getitem__(self, key)
        if time.time() - val.timestamp > self.expire_time:
            del self[key]
            raise KeyError(key)
        else:
            return val.value

    # other dict methods overridden

if __name__ == '__main__':

    d = ExpireDict(2)

    d["a"] = "b"
    d["b"] = "c"

    time.sleep(1)

    assert d["a"] == "b"

    time.sleep(1)

    try:
        d["a"]
        assert False
    except KeyError:
        pass

@alanfranz
Copy link

zzzeek: consider using an abc instead so you can have full control on where the key is removed. Your implementation will fail by exchanging d["a"] with "a" in d, as an example.

@zzzeek
Copy link

zzzeek commented Mar 3, 2011

yup, many methods will fail in this partial example including d.values(). was just to illustrate the method of associating timestamp.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment