Alex Gaudio

Dynamic Inheritance In Python

Dynamic Inheritance is useful when you need to instantiate an object whose base class is only known at the time of instantiation.

For instance, I have a few different sequences:

a=[1,2,3]printtype(a)b=(4,5,6)printtype(b)c={7:1,8:1,9:1}printtype(c)

And I want to instantiate an object that inherits the same class as one of the above input sequences. Unfortunately, I can’t know which sequence I will inherit from until the program is about to instantiate my object.

Rather than answering the question outright, this post will explain how dynamic inheritance works by example, but will leave the particular implementation of this problem to the reader. So\u2026 how can one dynamically inherit a class at time of instantiation?

One option is to define a factory function and a nested class definition to dynamically build and return a class:

defmake(cls):"""Return a NewClass that inherits from given class object (not an instance of a class)"""classNewClass(cls):passreturnNewClassNewClass=make(list)printNewClass.__bases__# the list of classes NewClass inherits from
newclass_instance=NewClass([1,2,3])

Taking this a step further, you can return an instance that dynamically inherits a class type:

defmakeinst(cls,*args,**kwargs):"""Return an instance of NewClass that inherits from given cls, initialized with given params"""classNewClass(cls):passreturnNewClass(*args,**kwargs)newclass_instance=makeinst(list,(4,5,6))

Which leads us to implement a MixIn: (This means that the cls will have all its methods + the methods in the mixin at its disposal. Super useful!)

Or you can pass in an instance and let your NewClass inherit the same type that the instance is.

defmakeinst2(instance):classNewClass(instance.__class__):pass# assume instance.__init__(instance.__repr__()) will work
returnNewClass(instance)

As you can see, there are several variations of saying, more or less, the same thing. The above code shows you how to mash classes together using inheritance. The approach of using a nested class inside a function isn’t the only approach. Python’s type() builtin provides really cool builtin ways of doing this: