Pickling dynamically generated classes? Pickling dynamically generated classes? python python

Pickling dynamically generated classes?


When the Pickler encounters an object of a type it knows nothing about, it looks for a reduce method. Defining this method when you build your custom class using type should solve the problem of pickling.

If you provide initial args then in addition you might need to define a getnewargs method


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.


One idea would be to pickle a tuple with:

  1. The name of the dynamic class
  2. The subclass tuple (possibly in string form from repr())
  3. The class dictionary
  4. The actual instance

This would allow you to pickle a class and then reconstruct it later using type() and subclassing Unpickler.