diff --git a/expiringdict/__init__.py b/expiringdict/__init__.py index 3e2f298..8056fe0 100644 --- a/expiringdict/__init__.py +++ b/expiringdict/__init__.py @@ -26,7 +26,7 @@ class ExpiringDict(OrderedDict): - def __init__(self, max_len, max_age_seconds): + def __init__(self, max_len, max_age_seconds, callback=None): assert max_age_seconds >= 0 assert max_len >= 1 @@ -34,6 +34,7 @@ def __init__(self, max_len, max_age_seconds): self.max_len = max_len self.max_age = max_age_seconds self.lock = RLock() + self.callback = callback def __contains__(self, key): """ Return True if the dict has a key, else return False. """ @@ -43,6 +44,8 @@ def __contains__(self, key): if time.time() - item[1] < self.max_age: return True else: + if self.callback: + self.callback(item[0]) del self[key] except KeyError: pass @@ -62,6 +65,8 @@ def __getitem__(self, key, with_age=False): else: return item[0] else: + if self.callback: + self.callback(item[0]) del self[key] raise KeyError(key)