I would like to create a class with specified base classes dynamically. In order to do it, I implemented the following:
class A:
pass
class B:
pass
def create(cls):
class C(A, cls):
def __reduce__(self):
print("REDUCE")
return (create, (self.__class__.__bases__[-1],))
return C()
Note that I also added a custom __reduce__
to support pickle dumping. However, it works only of instances of the created class(because __reduce__
is not a class method).
import pickle
c = create(B)
pickle.dumps(c) # Success
pickle.dumps(c.__class__) # Error
REDUCE
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-102-25510ddce378> in <module>
2 c = create(B)
3 pickle.dumps(c)
----> 4 pickle.dumps(c.__class__)
AttributeError: Can't pickle local object 'create.<locals>.C'
How could I make the class itself to support pickle dumping?