在对象上腌制lru_cached函数

时间:2019-01-25 10:07:45

标签: python serialization pickle lru

作为并行化某些现有代码(带有多处理)的一部分,我遇到了需要腌制类似于下面的类的情况。

开始于:

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)

返回

_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,但这并没有改变。

2 个答案:

答案 0 :(得分:0)

正如评论中所详细描述的,在处理装饰器时,pickle模块有问题。有关更多详细信息,请参见此问题:

Pickle and decorated classes (PicklingError: not the same object)

答案 1 :(得分:0)

使用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