polo
polo

Reputation: 1452

How to define a python class at runtime with a dynamic inheritance chain?

I need an expert's help with the Python type system. Can I do something like:

class I(object): pass
class A(I): pass
class B(I): pass
my_parents = [A, B]
class C(*my_parents): pass

Basically I want to determine the inheritance chain at runtime, avoiding any potential issues resulting from the diamond problem. What's the best way to do something like that?

Upvotes: 0

Views: 883

Answers (1)

unutbu
unutbu

Reputation: 880987

You can define classes dynamically using the 3-argument form of type:

C = type('C', tuple(my_parents), {})

class I(object): pass
class A(I): pass
class B(I): pass
my_parents = [A, B]
# class C(*my_parents): pass # works in Python3 but not in Python2
C = type('C', tuple(my_parents), {})
print(C.__bases__)

yields

(<class '__main__.A'>, <class '__main__.B'>)

Note: I don't know what you mean by "avoiding any potential issues resulting from the diamond problem". You will have an inheritance diamond if you use A and B as bases of C. If the issue you are referring to is how to call parent methods, the solution of course is to use super.

Upvotes: 2

Related Questions