Common Lisp has defvar
which
creates a global variable but only sets it if it is new: if it already
exists, it is not reset. This is useful when reloading a file from a long running interactive process, because it keeps the data.
I want the same in Python.
I have file foo.py
which contains something like this:
cache = {}
def expensive(x):
try:
return cache[x]
except KeyError:
# do a lot of work
cache[x] = res
return res
When I do imp.reload(foo)
, the value of cache
is lost which I want
to avoid.
How do I keep cache
across reload
?
PS. I guess I can follow How do I check if a variable exists? :
if 'cache' not in globals():
cache = {}
but it does not look "Pythonic" for some reason... If it is TRT, please tell me so!
Answering comments:
- I am not interested in cross-invocation persistence; I am already handling that.
- I am painfully aware that reloading changes class meta-objects and I am already handling that.
- The values in
cache
are huge, I cannot go to disk every time I need them.