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

Clean up on length call to give accurate dictionary length based on expiration #40

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Delete keys after iterating to prevent mutation during iter
chanchiem committed Aug 2, 2019
commit cea1c3a167eabaf412a16ad4eb0967780f72093b
5 changes: 4 additions & 1 deletion expiringdict/__init__.py
Original file line number Diff line number Diff line change
@@ -58,14 +58,17 @@ def __init__(self, max_len, max_age_seconds, items=None):
def __len__(self):
with self.lock:
current_key = iter(self)
keys_to_del = []
for k in current_key:
item = OrderedDict.__getitem__(self, k)
time_added = item[1]
item_age = time.time() - time_added
if item_age > self.max_age:
del self[k]
keys_to_del.append(k)
else:
break
for k in keys_to_del:
del self[k]

return super(ExpiringDict, self).__len__()

2 changes: 1 addition & 1 deletion tests/expiringdict_test.py
Original file line number Diff line number Diff line change
@@ -65,7 +65,7 @@ def test_repr():
d['a'] = 'x'
eq_(str(d), "ExpiringDict([('a', 'x')])")
sleep(0.01)
eq_(str(d), "ExpiringDict()")
eq_(str(d), "ExpiringDict([])")


def test_iter():