2013-01-07 29 views
2

道歉,如果這已在其他地方回答。我看了看周圍的互聯網,並沒有找到明確的答案獲得例外pickle.dump

我有一個類的定義(包含多個值和方法),以及在列表中保存的類的多個實例。 (每個列表條目都是一個實例)。

當我嘗試醃製列表時,出現「pickle.PicklingError」異常。這讓我瞭解到有些對象不是'pickleable'的,但是看起來我的簡單列表應該沒問題。

哪些對象不可打開?

這裏是進行酸洗的實際代碼。 (此代碼是其中還包含我需要酸洗類對象的一類中定義的方法。是問題的一部分?)

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' 

回答

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). 
+0

嗯。這可能是問題所在。這裏所有相關的東西都是一個類的屬性,稱之爲類A.類A包含另一個類B類的定義(這只是在此使用)。被醃製的對象是A類的一個屬性,它是B類的實例化列表。執行酸洗的功能是A類中的方法。 我不能說,這種情況是否構成「嵌套類不在模塊範圍「? 感謝您的幫助。 – gearhead

+0

如果該類包含定義另一個類,那麼這是一個問題,是的。 – root

+0

也閱讀http://stackoverflow.com/questions/1947904/how-can-i-pickle-a-nested-class-in-python,有一些hackish解決方法 - 儘可能重構你的類最好的靈魂。 – root