from __future__ import annotations from collections import OrderedDict from typing import Generic, Iterator, TypeVar K = TypeVar("K") V = TypeVar("V") class LRUCache(Generic[K, V]): """Small LRU cache backed by insertion order.""" def __init__(self, capacity: int) -> None: if capacity <= 0: raise ValueError("capacity must be positive") self.capacity = capacity self._items: OrderedDict[K, V] = OrderedDict() def get(self, key: K, default: V | None = None) -> V | None: """Return a value and mark it as recently used.""" if key not in self._items: return default self._items.move_to_end(key) return self._items[key] def put(self, key: K, value: V) -> None: """Insert or update an item, evicting the oldest when full.""" if key in self._items: self._items.move_to_end(key) self._items[key] = value if len(self._items) > self.capacity: self._items.popitem(last=False) def __contains__(self, key: object) -> bool: return key in self._items def __len__(self) -> int: return len(self._items) def __iter__(self) -> Iterator[K]: return iter(self._items) def __repr__(self) -> str: return f"LRUCache(capacity={self.capacity}, items={dict(self._items)!r})" def test_evicts_least_recently_used() -> None: cache: LRUCache[str, int] = LRUCache(capacity=2) cache.put("a", 1) cache.put("b", 2) cache.put("c", 3) assert cache.get("a") is None assert cache.get("b") == 2 assert cache.get("c") == 3 def test_get_refreshes_usage() -> None: cache: LRUCache[str, int] = LRUCache(capacity=2) cache.put("a", 1) cache.put("b", 2) assert cache.get("a") == 1 cache.put("c", 3) assert cache.get("a") == 1 assert cache.get("b") is None assert cache.get("c") == 3 if __name__ == "__main__": test_evicts_least_recently_used() test_get_refreshes_usage()