Skip to content

Commit dcf0a01

Browse files
fix: correctly handle falsy values in LRUCache
1 parent 10644a0 commit dcf0a01

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

tests/test_utils.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,32 @@ def test_lru_cache_iteration_works():
9696
assert count == 0
9797

9898

99+
def test_lru_cache_falsy_values_bug():
100+
"""
101+
Test for GitHub issue #596: LRU cache should handle falsy values correctly.
102+
103+
Bug: `if self.cache.get(key):` treated falsy values as non-existent keys,
104+
breaking LRU ordering when updating existing keys with falsy values.
105+
"""
106+
cache = LRUCache(capacity=3)
107+
108+
# Set up cache with falsy value
109+
cache["a"] = 0 # Falsy value
110+
cache["b"] = 1
111+
cache["c"] = 2
112+
113+
assert cache.lru == ["a", "b", "c"]
114+
115+
# Update existing key with falsy value - should move to end
116+
cache.set("a", 3)
117+
assert cache.lru == ["b", "c", "a"]
118+
119+
# Add new item - should evict oldest ("b"), not "a"
120+
cache.set("d", 4)
121+
assert cache.lru == ["c", "a", "d"]
122+
assert "b" not in cache
123+
assert cache["a"] == 3
124+
99125
def test_freeze():
100126
frozen = freeze([0, 1, 2, {'a': [1, 2, 3]}, {1, 2}])
101127
assert isinstance(frozen, tuple)

tinydb/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def get(self, key: K, default: Optional[D] = None) -> Optional[Union[V, D]]:
9898
return default
9999

100100
def set(self, key: K, value: V):
101-
if self.cache.get(key):
101+
if key in self.cache:
102102
self.cache[key] = value
103103
self.cache.move_to_end(key, last=True)
104104
else:

0 commit comments

Comments
 (0)