Python dynamic inheritance and factory methods

Python supports dynamic inheritance which means you can declare a class parent at runtime. This can be applied to a class declaration nested in a method, giving the ability to create versatile “factory” methods. As an example:

def factory(parent):
    class Subclass(parent):
        def __init__(self, message):
            parent.__init__(self, message)

    return Subclass

This will create a subclass with parent as a parent as return the class definition. If we now define two base classes:

class ParentZombie:
    def __init__(self, message):
        print(f"I am the ZOMBY WOOF: {message}")


class ParentWoof:
    def __init__(self, message):
        print(f"Tellin' you all the Zomby troof: {message}")

We can now decide the subclass at runtime. For instance:

Zombie = factory(ParentZombie)
Zombie("woof!")

Will print I am the ZOMBY WOOF: woof! and:

Zombie = factory(ParentWoof)
Zombie("woof!")

Will print Tellin' you all the Zomby troof: woof!.

I haven’t found a situation where I needed this, but it’s good to know it is possible.