如何判断哪个对象属性泡菜失败? [英] How to tell for which object attribute pickle fails?
问题描述
当您腌制具有某些无法腌制的属性的对象时,它将失败并显示一般错误消息,例如:
When you pickle an object that has some attributes which cannot be pickled it will fail with a generic error message like:
PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
有什么办法可以判断是哪个属性导致了异常?我使用的是 Python 2.5.2.
Is there any way to tell which attribute caused the exception? I am using Python 2.5.2.
即使我原则上理解问题的根本原因(例如,在上面的例子中有一个实例方法),但仍然很难准确地查明它.在我的例子中,我已经定义了一个自定义的 __getstate__
方法,但是忘记了一个关键属性.这发生在嵌套对象的复杂结构中,所以我花了一段时间来识别错误的属性.
Even though I understand in principle the root cause of the problem (e.g. in the above example having an instance method) it can still be very hard to exactly pinpoint it. In my case I already defined a custom __getstate__
method, but forgot about a critical attribute. This happened in a complicated structure of nested objects, so it took me a while to identify the bad attribute.
根据要求,这里是一个简单的例子,pickle 故意失败:
As requested, here is one simple example were pickle intentionally fails:
import cPickle as pickle
import new
class Test(object):
pass
def test_func(self):
pass
test = Test()
pickle.dumps(test)
print "now with instancemethod..."
test.test_meth = new.instancemethod(test_func, test)
pickle.dumps(test)
这是输出:
now with instancemethod...
Traceback (most recent call last):
File "/home/wilbert/develop/workspace/Playground/src/misc/picklefail.py", line 15, in <module>
pickle.dumps(test)
File "/home/wilbert/lib/python2.5/copy_reg.py", line 69, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects
不幸的是,没有迹象表明属性 test_meth
导致了问题.
Unfortunately there is no hint that the attribute test_meth
causes the problem.
推荐答案
您可以针对 Python 提交错误,因为没有包含更多有用的错误消息.同时修改copy_reg.py
中的_reduce_ex()
函数.
You could file a bug against Python for not including more helpful error messages. In the meantime, modify the _reduce_ex()
function in copy_reg.py
.
if base is self.__class__:
print self # new
raise TypeError, "can't pickle %s objects" % base.__name__
输出:
<bound method ?.test_func of <__main__.Test object at 0xb7f4230c>>
Traceback (most recent call last):
File "nopickle.py", line 14, in ?
pickle.dumps(test)
File "/usr/lib/python2.4/copy_reg.py", line 69, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects
这篇关于如何判断哪个对象属性泡菜失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!