我想像这样pickle-dump一个对象:
import module_A
import module_B
class SomeClass(object):
def __init__(self, the_module):
self.module = the_module
self.some_other_members = whatever
x = SomeClass(module_A)
这是不允许的,错误是我无法转储模块。在这种情况下,我对实际转储模块不感兴趣。然而,对象正在使用哪个模块很重要。所以我想转储模块的一些标识符,例如 __setstate__
我可以指self.module
到正确的模块。我应该使用什么样的标识符来 __setstate__
我可以通过该标识符找到正确的模块吗?可能有许多可能的模块和类 SomeClass
现在知道其中有哪些了。
更新:
抱歉,我们在使用 cPickle
时发现了错误消息。普通pickle
没有这个问题,正如迈克提到的,dill
也支持 pickle 模块。我使用的最终解决方案是此处给出的解决方案:https://mail.python.org/pipermail/python-ideas/2013-July/021959.html .
最佳答案
我认为您可以使用 dill
完成您想要的操作,它提供了比 pickle
更好的序列化。
>>> import dill
>>> import numpy
>>>
>>> import math
>>>
>>> class SomeClass(object):
... def __init__(self, module):
... self.module = module
... self.other = lambda x: numpy.arange(3)
...
>>> # save the class instance
>>> x = SomeClass(math)
>>> _x = dill.dumps(x)
>>>
>>> # delete a bunch of stuff
>>> del SomeClass
>>> del math
>>> import sys
>>> del sys.modules['math']
>>> del x
>>>
>>> # unpickle
>>> x = dill.loads(_x)
>>> x.module
>>> x.module.sin(x.other(0)[0])
0.0
关于python - Pickle 转储引用模块的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31953897/