Skip to content

Commit

Permalink
Delete keys after iterating to prevent mutation during iter
Browse files Browse the repository at this point in the history
  • Loading branch information
chanchiem committed Aug 2, 2019
1 parent 4f4b2df commit cea1c3a
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 2 deletions.
5 changes: 4 additions & 1 deletion expiringdict/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__()

Expand Down
2 changes: 1 addition & 1 deletion tests/expiringdict_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down

0 comments on commit cea1c3a

Please sign in to comment.