openmmtools.cache.LRUCache¶
- class openmmtools.cache.LRUCache(capacity=None, time_to_live=None)[source]¶
A simple LRU cache with a dictionary-like interface that supports maximum capacity and expiration.
It can be configured to have a maximum number of elements (capacity) and an element expiration (time_to_live) measured in number of accesses to the cache. Both read and write operations count as an access, but only successful reads (i.e. those not raising KeyError) increment the counter.
- Parameters:
- capacityint, optional
Maximum number of elements in the cache. When set to None, the cache has infinite capacity (default is None).
- time_to_liveint, optional
If an element is not accessed after time_to_live read/write operations, the element is removed. When set to None, elements do not have an expiration (default is None).
Examples
>>> cache = LRUCache(capacity=2, time_to_live=3)
When the capacity is exceeded, the least recently used element is removed.
>>> cache['1'] = 1 >>> cache['2'] = 2 >>> elem = cache['1'] # read '1', now '2' is the least recently used >>> cache['3'] = 3 >>> len(cache) 2 >>> '2' in cache False
After time_to_live read/write operations an element is deleted if it is not used.
>>> elem = cache['3'] # '3' is used, counter is reset >>> elem = cache['1'] # access 1 >>> elem = cache['1'] # access 2 >>> elem = cache['1'] # access 3 >>> len(cache) 1 >>> '3' in cache False
- Attributes:
capacity
Maximum number of elements that can be cached.
time_to_live
Number of read/write operations before an cached element expires.
Methods
empty
()Purge the cache.
Methods
__init__
([capacity, time_to_live])empty
()Purge the cache.
Attributes
capacity
Maximum number of elements that can be cached.
time_to_live
Number of read/write operations before an cached element expires.