LRU Cache with eviction callback
Project description
We can use Python built-in functions.lru_cache, but when a cached item is evicted, there is no chance to release corresponding resources.
This LRU Cache with callback feature provides the similar usage as functions.lru_cache with decorator @lru_cache. Plus, it can task a eviction_callback function to do clean works. The function signature is callback(key, value).
Basic LRU Cache
@lru_cache(3)
def fetch(x):
print('miss:', x, end='')
return x + 1
for i in [1, 2, 3, 1, 2, 4, 3, 2, 1]:
print(f'get data for {i}: ', end='')
fetch(i)
print()
Output:
get data for 1: miss: 1
get data for 2: miss: 2
get data for 3: miss: 3
get data for 1:
get data for 2:
get data for 4: miss: 4
get data for 3: miss: 3
get data for 2:
get data for 1: miss: 1
LRU Cache with callback for eviction
def eviction_callback(key, value):
# release resources
print(f"evicted key: {key}, {value}", end='')
@lru_cache(3, evict_callback=eviction_callback)
def fetch(x):
print(f'miss: {x}, ', end='')
return x + 1
for i in [1, 2, 3, 1, 2, 4, 3, 2, 1]:
print(f'get data for {i}: ', end='')
fetch(i)
print()
Output:
get data for 1: miss: 1,
get data for 2: miss: 2,
get data for 3: miss: 3,
get data for 1:
get data for 2:
get data for 4: miss: 4, evicted key: 3, 4
get data for 3: miss: 3, evicted key: 1, 2
get data for 2:
get data for 1: miss: 1, evicted key: 4, 5
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
No source distribution files available for this release.See tutorial on generating distribution archives.
Built Distribution
File details
Details for the file callback_lru_cache-0.0.7-py3-none-any.whl
.
File metadata
- Download URL: callback_lru_cache-0.0.7-py3-none-any.whl
- Upload date:
- Size: 2.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 968d807e16186eb47912730a98470c3ed04aa8e14297d59d60917cffcf24a58b |
|
MD5 | fedc6bb3fdbd9661f2a9e82bf07c5602 |
|
BLAKE2b-256 | fd0f1adf1527a73f9def9096142c955529a27be63e0ef1cb76fd13b0ac144f7c |