假设我有一些创建多个变量的代码:
# Some code
# Beginning of the block to memoize
a = foo()
b = bar()
...
c =
# End of the block to memoize
# ... some more code
我想记住上面的整个块,而不必明确说明块中创建/更改的每个变量或手动腌制它们。我怎样才能在 Python 中做到这一点?
理想情况下,我希望能够用一些东西(if/else
或with
语句)包装它,并有一个标志,如果我愿意,可以强制刷新。
从概念上讲,它会像:
# Some code
# Flag that I can set from outside to save or force a reset of the chache
refresh_cache = True
if refresh_cache == False
load_cache_of_block()
else:
# Beginning of the block to memoize
a = foo()
b = bar()
...
c = stuff()
# End of the block to memoize
save_cache_of_block()
# ... some more code
有什么方法可以做到这一点,而不必显式腌制代码中定义或更改的每个变量?(即在第一次运行结束时我们保存,然后我们只是重用这些值)