Dynamic inheritance in Python

Question:

Say I have 2 different implementations of a class

class ParentA:
    def initialize(self):
        pass

    def some_event(self):
        pass

    def order(self, value):
        # handle order in some way for Parent A


class ParentB:
    def initialize(self):
        pass

    def some_event(self):
        pass

    def order(self, value):
        # handle order in another for Parent B

How can I dynamically let some 3rd class inherit from either ParentA or ParentB based on something like this?

class MyCode:
    def initialize(self):
        self.initial_value = 1

    def some_event(self):
        # handle event
        order(self.initial_value)


# let MyCode inherit from ParentA and run
run(my_code, ParentA)
Asked By: Morten

||

Answers:

Simply store the class-object in a variable (in the example below, it is named base), and use the variable in the base-class-spec of your class statement.

def get_my_code(base):

    class MyCode(base):
        def initialize(self):
          ...

    return MyCode

my_code = get_my_code(ParentA)
Answered By: shx2

Also, you can use type builtin. As callable, it takes arguments: name, bases, dct (in its simplest form).

def initialize(self):
    self.initial_value = 1

def some_event(self):
    # handle event
    order(self.initial_value)

subclass_body_dict = {
    "initialize": initialize,
    "some_event": some_event
}

base_class = ParentA # or ParentB, as you wish

MyCode = type("MyCode", (base_class, ), subclass_body_dict)

This is more explicit than snx2 solution, but still – I like his way better.

PS. of course, you dont have to store base_class, nor subclass_body_dict, you can build those values in type() call like:

MyCode = type("MyCode", (ParentA, ), {
        "initialize": initialize,
        "some_event": some_event
    })
Answered By: Filip Malczak

Just as a quick copy-and-paste-ready snippet, I’ve added the comments from shx2’s answer to create this (memoized with a created_classes dict attribute, so that the classes created by successive identical calls with the same class will give identical classes):

class ParentA:
    val = "ParentA"

class ParentB:
    val = "ParentB"

class DynamicClassCreator():
    def __init__(self):
        self.created_classes = {}
    def __call__(self, *bases):
        rep = ",".join([i.__name__ for i in bases])
        if rep in self.created_classes:
            return self.created_classes[rep]
        class MyCode(*bases):
            pass
        self.created_classes[rep] = MyCode
        return MyCode

creator = DynamicClassCreator()

instance1 = creator(ParentA, ParentB)()
print(instance1.val) #prints "ParentA"

instance2 = creator(ParentB, ParentA)()
print(instance2.val) #prints "ParentB"

If you wanted to get fancy you could even make DynamicClassCreator a Singleton: https://stackoverflow.com/a/7346105/5122790

Answered By: Chris Stenkamp

As an alternative to Chris’s answer implementing the memoisation suggestion for shx2’s answer, I’d prefer to use a memoize decorator (the end result is still a class but it’s clearer to me that the function is the interface), and also use setdefault to simplify adding to the memo dict, and do not convert the names to string but use the tuple bases itself as the key, simplifying the code to:

class Memoize:
    def __init__(self, f):
        self.f = f
        self.memo = {}

    def __call__(self, *args):
        return self.memo.setdefault(args, self.f(*args))

class ParentA:
    def initialize(self):
        pass


class ParentB:
    def initialize(self):
        pass


@Memoize
def get_my_code(base):

    class MyCode(base):
        def initialize(self):
          pass

    return MyCode

a1 = get_my_code(ParentA)
a2 = get_my_code(ParentA)
b1 = get_my_code(ParentB)

print(a1 is a2) # True
print(a1 is b1) # False

(Not a good example as the code provided doesn’t actually do anything other than overwrite the parent class’s initialize method…)

Answered By: Louis Maddox
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.