使用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

发布了62 篇原创文章 · 获赞 11 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/real_ilin/article/details/105257568
今日推荐