fix: LRUCache.get() and __getitem__() fail for cached None values#623
Open
koteshyelamati wants to merge 1 commit into
Open
fix: LRUCache.get() and __getitem__() fail for cached None values#623koteshyelamati wants to merge 1 commit into
koteshyelamati wants to merge 1 commit into
Conversation
When a cached value is None, LRUCache.get() incorrectly returns the default instead of the cached None, and LRUCache.__getitem__() raises KeyError even though the key exists. Root cause: both methods check `if value is not None` / `if value is None` to detect cache misses, but this fails when None is a legitimate cached value. Fix: check `if key not in self.cache` instead, mirroring the fix applied to LRUCache.set() in PR msiemens#597. Reproducer: cache = LRUCache(capacity=5) cache['key'] = None assert cache.get('key', 'default') == None # fails before fix assert cache['key'] is None # raises KeyError before fix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
LRUCache.get()andLRUCache.__getitem__()both break whenNoneis a legitimate cached value.get()bug: usesif value is not None:to detect cache hits, so if a key maps toNone, it skips the LRU promotion and returns thedefaultinstead of the cachedNone.__getitem__()bug: callsself.get(key)and then checksif value is None: raise KeyError, so it raisesKeyErroreven when the key exists with valueNone.Root cause
Both methods use the cached value itself as a sentinel to detect cache misses. This is the same class of bug that was fixed in
set()by PR #597.Fix
Replace the value-based checks with
key not in self.cachemembership tests, consistent with howset()was already fixed.