使用pickle時遇到TypeError: can't pickle _thread.RLock object

兩次遇到這個問題,但是原因不同:

第一次是調用sklearn的包進行多線程訓練時,需要傳入一個參數是一個clallabe的函數,我把這個函數與訓練的函數放到同一個類裏,傳入時用的是processor=self.my_processor,後面的my_porcessor是自己封裝的方法,processor是要多線程訓練的一個參數。

後面解決的方法是把my_processor函數封裝到這個類的外面,processor=my_processor這樣傳入的。

第二次是使用pickle.dumps()時遇到這個問題的,需要dumps的對象是一個Config對象,但是這個對象中放入了Logger對象。然後在dumps的時候報錯。

原因是:pickle不能序列化一些複雜對象。可以序列化的類型如下:
The following types can be pickled:

  • None, True, and False
  • integers, floating point numbers, complex numbers
  • strings, bytes, bytearrays
  • tuples, lists, sets, and dictionaries containing only picklable objects
  • functions defined at the top level of a module (using def, not lambda)
  • 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 Pickling Class Instances for details).

參考:https://docs.python.org/3/library/pickle.html#pickle-inst

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章