已经有几年了,但如果您的代码允许您重构为单独的函数,您可以轻松调用func.clear()
以选择性地从缓存中删除该函数。
示例代码:
#!/usr/bin/env python
import sys
from shutil import rmtree
import joblib
cachedir = "joblib-cache"
memory = joblib.Memory(cachedir)
@memory.cache
def foo():
print("running foo")
return 42
@memory.cache
def oof():
print("running oof")
return 24
def main():
rmtree(cachedir)
print(f"{sys.version=}")
print(f"{joblib.__version__=}")
print(foo())
print(oof())
print()
print("*" * 20 + " These should now be cached " + "*" * 20)
print(foo())
print(oof())
print()
foo.clear()
print("*" * 20 + " `foo` should now be recaculated " + "*" * 20)
print(foo())
print(oof())
if __name__ == "__main__":
main()
输出:
sys.version='3.9.6 (default, Jun 30 2021, 10:22:16) \n[GCC 11.1.0]'
joblib.__version__='1.0.1'
________________________________________________________________________________
[Memory] Calling __main__--tmp-tmp.DaQHHlsA2H-clearcache.foo...
foo()
running foo
______________________________________________________________foo - 0.0s, 0.0min
42
________________________________________________________________________________
[Memory] Calling __main__--tmp-tmp.DaQHHlsA2H-clearcache.oof...
oof()
running oof
______________________________________________________________oof - 0.0s, 0.0min
24
******************** These should now be cached ********************
42
24
WARNING:root:[MemorizedFunc(func=<function foo at 0x7f9cd7d8e040>, location=joblib-cache/joblib)]: Clearing function cache identified by __main__--tmp-tmp/DaQHHlsA2H-clearcache/foo
******************** `foo` should now be recaculated ********************
________________________________________________________________________________
[Memory] Calling __main__--tmp-tmp.DaQHHlsA2H-clearcache.foo...
foo()
running foo
______________________________________________________________foo - 0.0s, 0.0min
42
24