Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

call callback with expired items #19

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion expiringdict/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,15 @@


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

OrderedDict.__init__(self)
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. """
Expand All @@ -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
Expand All @@ -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)

Expand Down