Pickling dynamically generated classes?

后端 未结 6 810
野性不改
野性不改 2020-12-24 11:48

I\'m using type() to dynamically generate classes that will ultimately be pickled. The problem is that the un-pickling process needs the definition of the class

6条回答
  •  太阳男子
    2020-12-24 12:22

    For non-dynamic classes, python's pickling mechanism records the module and class name as strings. At unpickle time, it automatically loads the class object from that module.

    As mentioned in the original post, the problem here is that for dynamic classes, the class definition itself is not pickled by the default pickler. Since dynamic classes don't exist in a module's source file, unpickling a dynamic class generally won't work.

    The trickiest part of pickling the class itself is storing the methods' bytecode. Buried in PiCloud, there's an enhanced pickler under the hood that can pickle dynamic functions you could probably use or extend it to handle your objects.

提交回复
热议问题