instance_cache
为类实例方法提供实例级的结果缓存, 不影响类实例正常垃圾回收的装饰器
0. 背景
functools.lru_cache 和 cache 函数会保留对调用参数的强引用, 会影响这些参数正常的垃圾回收,
需要等待缓存超过 max_size 后弹出或手动调用 cache_clear, 比较麻烦.
最常见的场景是作用在类实例方法上, 保留参数 self 的引用后会影响整个类实例的垃圾回收.
>>> from functools import cache
>>>
>>> class MyClass:
... def normal_method(self):
... ...
...
... @cache
... def cached_method(self):
... ...
...
... def __del__(self):
... print('delete!')
...
>>> MyClass().normal_method() # 正常垃圾回收
delete!
>>> MyClass().cached_method() # 无法进行垃圾回收
>>> MyClass().cached_method()
>>> MyClass().cached_method()
>>> MyClass.cached_method.cache_clear() # 手动清理缓存才会回收
delete!
delete!
delete!
此处提供一个类实例方法的结果缓存装饰器, 提供实例级别的缓存 (为每个实例单独创建缓存空间).
通过将缓存内容作为每个类实例的属性进行存储 (类似于 functools.cached_property), 避免影响类实例 self 的正常垃圾回收.
其他调用参数在类实例被回收后也会正常回收.
1. 安装
使用以下命令安装该库
pip install instance_cache
2. 使用
使用方法非常简单, 与 functools.lru_cache 基本一致
>>> from instance_cache import instance_cache
>>>
>>> class MyClass:
... @instance_cache()
... def cached_method(self, x=1, y=2):
... print('run')
... ... # 耗时操作
... return 1
...
... def __del__(self):
... print('delete!')
...
>>> foo = MyClass()
>>> foo.cached_method(1, 2)
run
1
>>> foo.cached_method(1, 2) # 命中缓存, 不运行方法直接返回结果
1
>>> MyClass.cached_method.cache_info(foo) # 查看实例的缓存信息
CacheInfo(hits=1, misses=1, maxsize=128, currsize=1)
>>> # MyClass.cached_method.cache_clear(foo) # 清空实例的缓存并重置缓存信息
>>> del foo # 立刻进行垃圾回收
delete!
Metadata
Release files for instance-cache 0.2.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| instance_cache-0.2.1.tar.gz | 7.5 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| instance_cache-0.2.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 16.4 kB
Release files / instance_cache-0.2.1.tar.gz
| Download URL | instance_cache-0.2.1.tar.gz |
|---|---|
| Size | 7.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f8c4903e9a4fbf13305e7075d5a0a5a9d5d597ed02b767901906987db8be0303
|
|
BLAKE2b-256 checksum How to use checksums |
1c278dd709e7ac0fd04437d9c28fbe6c0405171152541810fb0eb62cb678f763
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.0
|
Release files / instance_cache-0.2.1-py3-none-any.whl
| Download URL | instance_cache-0.2.1-py3-none-any.whl |
|---|---|
| Size | 8.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
dfa1785f79b7e5589fb72e5af7ec8512a1531256ad25b379b4bda4177f2c4e99
|
|
BLAKE2b-256 checksum How to use checksums |
ec09072ea64cafbcb3d28cd7d50dc725929bc114b9bd36e780423fc6464c7250
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.0
|