<p>这里有几个选择。一种是使用临时文件作为缓存的持久存储,并在每次加载模块时尝试加载:</p>
<pre><code># foo.py
import tempfile
import pathlib
import pickle
_CACHE_TEMP_FILE_NAME = '__foo_cache__.pickle'
_CACHE = {}
def expensive(x):
try:
return _CACHE[x]
except KeyError:
# do a lot of work
_CACHE[x] = res
_save_cache()
return res
def _save_cache():
tmp = pathlib.Path(tempfile.gettempdir(), _CACHE_TEMP_FILE_NAME)
with tmp.open('wb') as f:
pickle.dump(_CACHE, f)
def _load_cache():
global _CACHE
tmp = pathlib.Path(tempfile.gettempdir(), _CACHE_TEMP_FILE_NAME)
if not tmp.is_file():
return
try:
with tmp.open('rb') as f:
_CACHE = pickle.load(f)
except pickle.UnpicklingError:
pass
_load_cache()
</code></pre>
<p>唯一的问题是,您需要相信环境不会编写任何恶意文件来代替临时文件(对于错误或恶意构造的数据,<code>pickle</code>模块是不安全的)。你知道吗</p>
<p>另一种选择是为缓存使用另一个不会重新加载的模块:</p>
<pre><code># foo_cache.py
Cache = {}
</code></pre>
<p>然后:</p>
<pre><code># foo.py
import foo_cache
def expensive(x):
try:
return foo_cache.Cache[x]
except KeyError:
# do a lot of work
foo_cache.Cache[x] = res
return res
</code></pre>