How to test for order of superclass in python?

Viewed 76

Giving following code:

class X(Mixin, Y):
    pass

How can I write a unittest to ensure Mixin class is before Y in superclass declaration of X?

2 Answers

Don't test it. Unless you're writing tests for a Python implementation itself.

It's not the responsibility of your library's test suite to verify that the Python interpreter is working as designed. Mixin appears before Y in the declaration is self-evident when reading the code, and the fact that Python evaluates initializers left to right in a multiple inheritance is documented here.

Note: I'm not saying this behaviour should not be tested, just that such tests needn't be duplicated by user code. It should be covered in the test suite of the implementation, e.g. here for CPython.

You can parse the output of X.mro(), which returns the method resolution order and make sure that Mixin comes before Y:

class Mixin: pass

class Y: pass

class X(Mixin, Y): pass

print(X.mro())
# [<class '__main__.X'>, <class '__main__.Mixin'>, <class '__main__.Y'>, <class 'object'>]

However, I'm not sure that this is not an implementation detail and how much one can (or should) count on subclasses order. If your code depends on it, there may be something wrong in the design.

Related