I can “pickle local objects” if I use a derived class?

后端 未结 4 1622

The pickle reference states that the set of objects which can be pickled is rather limited. Indeed, I have a function which returns a dinamically-generated clas

4条回答
  •  难免孤独
    2020-12-05 03:14

    You can only pickle instances of classes defined at module's top level.

    However, you can pickle instances of locally-defined classes if you promote them to top level.

    You must set the __ qualname__ class attribute of the local class. Then you must assign the class to a top-level variable of the same name.

    def define_class(name):
        class local_class:
            pass
        local_class.__qualname__ = name
        return local_class
    
    class_A = define_class('class_A') # picklable
    class_B = define_class('class_B') # picklable
    class_X = define_class('class_Y') # unpicklable, names don't match
    

提交回复
热议问题