File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed
Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ # Copyright 2025 Google LLC
2+ #
3+ # Licensed under the Apache License, Version 2.0 (the "License");
4+ # you may not use this file except in compliance with the License.
5+ # You may obtain a copy of the License at
6+ #
7+ # https://www.apache.org/licenses/LICENSE-2.0
8+ #
9+ # Unless required by applicable law or agreed to in writing, software
10+ # distributed under the License is distributed on an "AS IS" BASIS,
11+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+ # See the License for the specific language governing permissions and
13+ # limitations under the License.
14+
115from collections import OrderedDict
216
317
@@ -11,6 +25,14 @@ def clear(self):
1125 super ().clear ()
1226 self ._order .clear ()
1327
28+ def get (self , key , default = None ):
29+ try :
30+ value = super ().__getitem__ (key )
31+ self ._update (key )
32+ return value
33+ except KeyError :
34+ return default
35+
1436 def __getitem__ (self , key ):
1537 value = super ().__getitem__ (key )
1638 self ._update (key )
Original file line number Diff line number Diff line change 22
33
44def test_lru_cache ():
5+ """Test the LRUCache for generally expected functionality and ordering."""
56 lru_cache = LRUCache (2 )
67 lru_cache ["a" ] = 1
78 lru_cache ["b" ] = 2
@@ -17,6 +18,31 @@ def test_lru_cache():
1718
1819
1920def test_zero_size_lru_cache ():
21+ """Confirm the LRUCache handles zero-size correctly."""
2022 lru_cache = LRUCache (0 )
2123 lru_cache ["a" ] = 1
2224 assert "a" not in lru_cache
25+
26+
27+ def test_lru_cache_get_updates_lru ():
28+ """Confirm the LRUCache handles get calls correctly."""
29+ lru_cache = LRUCache (2 )
30+ lru_cache ["a" ] = 1
31+ lru_cache ["b" ] = 2
32+
33+ # Access "a" via get(), making it MRU.
34+ assert lru_cache .get ("a" ) == 1
35+
36+ # Add "c", which should evict "b" (LRU), not "a".
37+ lru_cache ["c" ] = 3
38+
39+ assert "a" in lru_cache
40+ assert "b" not in lru_cache
41+ assert "c" in lru_cache
42+
43+
44+ def test_lru_cache_get_missing ():
45+ """Confirm the LRUCache handles missing keys correctly."""
46+ lru_cache = LRUCache (2 )
47+ assert lru_cache .get ("missing" ) is None
48+ assert lru_cache .get ("missing" , "default" ) == "default"
You can’t perform that action at this time.
0 commit comments