MRO = method resolution order

What is the MRO?

  • Method resolution order defines the order in which the base classes are searched when executing a method.
  • First, the method or attribute is searched within a class and then it follows the order we specified while inheriting.
  • In multiple inheritances, the methods are executed based on the order specified while inheriting the classes.

Old style

Old style classes use DLR or depth-first left-to-right algorithm for MRO whereas new style classes use C3 Linearization algorithm for method resolution while doing multiple inheritances.

Diamond Problem

Python doesn't have this problem because of the method resolution order.

C3 linearization algorithm

C3 linearization algorithm enforces following constraints

  • Child classes get checked before parents
  • Multiple parents get checked in the order listed.
  • If there are two valid choices for the next class, pick the one from the first parent.

C3 super-class linearization, it is based on 3 rules

  1. Inheritance graph determines the structure of method resolution order.
  2. Preserving local precedence ordering, i.e., visiting the super class only after the method of the local classes are visited.
  3. Monotonicity. If a class X precedes class Y in all linearization of the parents of a class, then it will also precedes class Y in the final linearization.
class A:
 pass

class B(A):
 pass

class D(B, A):
 pass

d = D()
d.__mro__ # D, B, A

Example from Python Cookbook

1. __init__ starts with Base, B, A, C because new classes should overwrite existing data. 2. C.__mro__ ⇒ (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.Base'>, <class 'object'>)
1. __init__ starts with Base, B, A, C because new classes should overwrite existing data. 2. C.__mro__ ⇒ (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.Base'>, <class 'object'>)

Mixins

A mixin is a special kind of multiple inheritance. There are two main situations where mixins are used:

  • You want to provide a lot of optional features for a class.
  • You want to use one particular feature in a lot of different classes.

References

SuperMade with Super