0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.