Class LRUCache
Introduction
This class is a class that stores data to memory. Unlike Singleton LRUCache, this class is not a singleton class. This means you must be sure to keep the instance of the class alive as long as you need the cache.
Examples
This example creates an instance of the LRUCache class with a maximum size of 10
.
Each time an item is accessed, it is moved to the front of the cache. If the cache is full, the least recently used item is removed and the new item is added to the front of the cache.
from ooodev.utils.cache import LRUCache
cache = LRUCache(max_size=10)
cache["key1"] = "value1"
cache["key2"] = "value2"
cache["key3"] = "value3"
print(cache["key1"]) # prints "value1"
print(cache["key2"]) # prints "value2"
print(cache["key3"]) # prints "value3"
del cache["key1"]
assert "key1" not in cache
Class
- class ooodev.utils.cache.LRUCache(capacity)[source]
Least Recently Used (LRU) Cache
- Parameters:
capacity (int) –
- __init__(capacity)[source]
Least Recently Used (LRU) Cache
- Parameters:
capacity (int) – Cache capacity.
- get(key)[source]
Get value by key.
- Parameters:
key (Any) – Any Hashable object.
- Returns:
Value or
None
if not found.- Return type:
Any
Note
The
get
method is an alias for the__getitem__
method. So you can usecache_inst.get(key)
orcache_inst[key]
interchangeably.
- put(key, value)[source]
Put value by key.
- Parameters:
key (Any) – Any Hashable object.
value (Any) – Any object.
- Return type:
None
Note
The
put
method is an alias for the__setitem__
method. So you can usecache_inst.put(key, value)
orcache_inst[key] = value
interchangeably.- Return type:
None
- Parameters:
key (Any) –
value (Any) –
- remove(key)[source]
Remove key.
- Parameters:
key (Any) – Any Hashable object.
- Return type:
None
Note
The
remove
method is an alias for the__delitem__
method. So you can usecache_inst.remove(key)
ordel cache_inst[key]
interchangeably.- Return type:
None
- Parameters:
key (Any) –
- property capacity: int
Gets/Sets Cache capacity.
Setting the capacity to 0 or less will clear the cache and effectively turn caching off. Setting the capacity to a lower value will remove the least recently used items.
- Returns:
Cache capacity.
- Return type:
int