Skip to content

Commit

Permalink
Internal: support iteration over LRUCache correctly
Browse files Browse the repository at this point in the history
Right now LRUCache is iterable due to its __getitem__ method which Python uses
with numerical indexes. But due to the current `get()` default value of `None`
it will iterate for ever always returning `None`. For now this commit fixes
this by making iteration over a LRUCache iterate the underlying dict instead.
  • Loading branch information
msiemens committed Sep 13, 2019
1 parent cb2ced1 commit 0475b23
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
9 changes: 9 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,15 @@ def test_lru_cache_unlimited_explicit():
assert len(cache.lru) == 100


def test_lru_cache_iteration_works():
cache = LRUCache()
count = 0
for _ in cache:
assert False, 'there should be no elements in the cache'

assert count == 0


def test_catch_warning():
class MyWarning(Warning):
pass
Expand Down
3 changes: 3 additions & 0 deletions tinydb/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ def __delitem__(self, key):
def __getitem__(self, key):
return self.get(key)

def __iter__(self):
return iter(self.__cache)

def get(self, key, default=None):
value = self.__cache.get(key)
if value:
Expand Down

0 comments on commit 0475b23

Please sign in to comment.