0

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?

Linkin
  • 1
  • I don't realy get what you want to do with that, what's the goal form creating a method that returns a class and take a another class `cls` just for nothing also the `A` class in it where's it's goal in all that – Walid Bousseta Aug 25 '21 at 15:48
  • Having some class (let's call it B), the goal is to create another class which inherits from B and A. I would like to do this creation in the runtime for many classes. In this concrete question, I just use the simple B to show the actual problem. – Linkin Aug 25 '21 at 15:52
  • Related question [here](https://stackoverflow.com/questions/4647566/pickle-a-dynamically-parameterized-sub-class/). Yes, this is possible via using a custom metaclass and `copyreg`. See also [issue 7689](https://bugs.python.org/issue7689). – Albert Apr 05 '23 at 20:48

1 Answers1

0

first you should know that __class__ is an attribute on the object that refers to the class from which the object was created. and from what you said I think this method answer it:

def create(cls):
     class C(A, cls):
         def classes(self):
             return A, cls
     return C()
Walid Bousseta
  • 1,329
  • 2
  • 18
  • 33