我从 Object
类型的 api 接收一个对象 t
。我无法 pickle 它,出现错误:
File "p.py", line 55, in <module>
pickle.dump(t, open('data.pkl', 'wb'))
File "/usr/lib/python2.6/pickle.py", line 1362, in dump
Pickler(file, protocol).dump(obj)
File "/usr/lib/python2.6/pickle.py", line 224, in dump
self.save(obj)
File "/usr/lib/python2.6/pickle.py", line 313, in save
(t.__name__, obj))
pickle.PicklingError: Can't pickle 'Object' object: <Object object at 0xb77b11a0>
当我执行以下操作时:
for i in dir(t): print(type(i))
我只得到字符串对象:
<type 'str'>
<type 'str'>
<type 'str'>
...
<type 'str'>
<type 'str'>
<type 'str'>
如何打印我的 Object
对象的内容以了解为什么它不能被 pickle?
该对象也可能包含指向 QT 对象的 C 指针,在这种情况下,我对该对象进行 pickle 是没有意义的。但我还是想看看对象的内部结构,以便确定这一点。
最佳答案
我会使用 dill
,它有工具来调查对象内部的什么导致目标对象不可 picklable。有关示例,请参见此答案:Good example of BadItem in Dill Module ,以及此问答以实际使用的检测工具为例:pandas.algos._return_false causes PicklingError with dill.dump_session on CentOS .
>>> import dill
>>> x = iter([1,2,3,4])
>>> d = {'x':x}
>>> # we check for unpicklable items in d (i.e. the iterator x)
>>> dill.detect.baditems(d)
[<listiterator object at 0x10b0e48d0>]
>>> # note that nothing inside of the iterator is unpicklable!
>>> dill.detect.baditems(x)
[]
但是,最常见的起点是使用trace
:
>>> dill.detect.trace(True)
>>> dill.detect.errors(d)
D2: <dict object at 0x10b8394b0>
T4: <type 'listiterator'>
PicklingError("Can't pickle <type 'listiterator'>: it's not found as __builtin__.listiterator",)
>>>
dill
还具有跟踪对象的指针引用和引用的功能,因此您可以构建对象如何相互引用的层次结构。请参阅:https://github.com/uqfoundation/dill/issues/58
或者,还有:cloudpickle.py 和 debugpickle.py,它们大部分已不再开发。我是 dill
的作者,希望尽快合并这些代码中 dill
中缺失的任何功能。
关于python - 确定为什么一个对象不能被 pickle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30499341/