Pickling dynamically generated classes?

后端 未结 6 827
野性不改
野性不改 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:20

    You can assign a global name to your dynamically generated class to make it picklable.

    >>> class Foo(object):
    ...     pass
    >>> class_name = 'Goo'
    >>> my_class = type(class_name, (Foo, ), {'run': lambda self, x: 2*x })
    >>> globals()[class_name] = my_class
    >>> g = my_class()
    >>> pickle.dumps(g)
    

    Of course, you need to make sure that the names of your classes are unique.

提交回复
热议问题