[docs]classLRUCache:"""A simple LRU cache implementation :param capacity: Maximum number of entries to keep. """def__init__(self,capacity:int)->None:self._lock=RLock()self._cache:OrderedDict[Hashable,Any]=OrderedDict()self.capacity=capacity
[docs]defget(self,key:Hashable)->Any:""" Get the cached value for a key. Mark as most recently used. :param key: Key to query. :returns: Cached value or None. """withself._lock:try:self._cache.move_to_end(key)returnself._cache[key]exceptKeyError:returnNone
[docs]defput(self,key:Hashable,value:Any)->None:""" Set the cached value for a key. Mark as most recently used. :param key: Key to use. Must be hashable. :param value: Value to cache. """withself._lock:self._cache[key]=valueself._cache.move_to_end(key)iflen(self._cache)>self.capacity:self._cache.popitem(last=False)
[docs]defclear(self)->None:""" Clears the cache. """withself._lock:self._cache.clear()