对象上的 pickling lru_cached 函数
pickling lru_cached function on object
作为并行化一些现有代码(使用多处理)的一部分,我 运行 遇到了类似于下面 class 的内容需要 pickle 的情况。
开始于:
import pickle
from functools import lru_cache
class Test:
def __init__(self):
self.func = lru_cache(maxsize=None)(self._inner_func)
def _inner_func(self, x):
# In reality this will be slow-running
return x
打电话
t = Test()
pickle.dumps(t)
returns
_pickle.PicklingError: Can't pickle <functools._lru_cache_wrapper object at 0x00000190454A7AC8>: it's not the same object as __main__.Test._inner_func
我不太明白。顺便说一句,我还尝试了一种变体,其中 _inner_func 的名称也为 func,但并没有改变。
如评论中所述,pickle 模块在处理装饰器时存在问题。有关详细信息,请参阅此问题:
使用methodtools.lru_cache
不在__init__
中新建缓存函数
import pickle
from methodtools import lru_cache
class Test:
@lru_cache(maxsize=None)
def func(self, x):
# In reality this will be slow-running
return x
if __name__ == '__main__':
t = Test()
print(pickle.dumps(t))
需要通过pypi安装methodtools:
pip install methodtools
作为并行化一些现有代码(使用多处理)的一部分,我 运行 遇到了类似于下面 class 的内容需要 pickle 的情况。
开始于:
import pickle
from functools import lru_cache
class Test:
def __init__(self):
self.func = lru_cache(maxsize=None)(self._inner_func)
def _inner_func(self, x):
# In reality this will be slow-running
return x
打电话
t = Test()
pickle.dumps(t)
returns
_pickle.PicklingError: Can't pickle <functools._lru_cache_wrapper object at 0x00000190454A7AC8>: it's not the same object as __main__.Test._inner_func
我不太明白。顺便说一句,我还尝试了一种变体,其中 _inner_func 的名称也为 func,但并没有改变。
如评论中所述,pickle 模块在处理装饰器时存在问题。有关详细信息,请参阅此问题:
使用methodtools.lru_cache
不在__init__
中新建缓存函数
import pickle
from methodtools import lru_cache
class Test:
@lru_cache(maxsize=None)
def func(self, x):
# In reality this will be slow-running
return x
if __name__ == '__main__':
t = Test()
print(pickle.dumps(t))
需要通过pypi安装methodtools:
pip install methodtools