获得一个例外pickle.dump

时间:2013-01-07 21:49:50

标签: python python-2.7

如果其他地方已经回答,请道歉。我环顾互联网并没有找到明确的答案

我有一个类定义(包含多个值和方法),以及列表中保存的类的多个实例。 (每个列表条目都是一个实例。)

当我尝试挑选列表时,我得到一个“pickle.PicklingError”异常。这让我了解到一些物体不是“可拾取的”,但似乎我的简单列表应该没问题。

哪些对象不可用?

这是进行酸洗的实际代码。 (这段代码是在类中定义的一个方法,它也包含我需要pickle的类对象。这是问题的一部分吗?)

def Write_Transaction_History_To_File(self):
    if (self.Transaction_History == True): # if History is not empty

        filename = self.Transaction_Name + '_Transaction_History.bin'
        f = open(filename, 'w')

        try:
            pickle.dump(self.Transaction_History , f, -1)   #use highest protocol
        except pickle.PicklingError:
            print 'Error when serializing data'
        f.close()

    else:
        print 'No History to store'

1 个答案:

答案 0 :(得分:3)

如果你试图挑选不在模块范围内的嵌套类,你将遇到麻烦。

来自docs

The following types can be pickled:


None, True, and False
integers, long integers, floating point numbers, complex numbers
normal and Unicode strings
tuples, lists, sets, and dictionaries containing only picklable objects
functions defined at the top level of a module
built-in functions defined at the top level of a module
classes that are defined at the top level of a module
instances of such classes whose __dict__ or the result of calling __getstate__() is 
picklable (see section The pickle protocol for details).