Contribute Media
A thank you to everyone who makes this possible: Read More

Method Resolution Order (MRO) in Python

Description

Imagine implementing inheritance in a programming language. At first, it looks like all the methods and attributes will be inherited by the child class. While it works for the majority of scenarios, as soon as we hit multiple-inheritance, deciding what method/attribute will take precedence, becomes a daunting task.

This is also known as the diamond problem. While some languages use an algorithm such as right-first-depth-first search to solve this, Python 2 used Depth-first from Left to Right (DLR) and Python3 uses C3 Linearization Algorithm. Getting hold of this information will help you not succumbing to the common pitfalls with the arrangement of name lookups in a class hierarchy.

MRO (Method Resolution Order) defines the class search path for linearizing the class ancestor tree. We’ll also have a look at how C3 algorithm is monotonic as it guarantees that base class declaration is preserved and subclasses appear before base classes. We’ll further explore MRO using __bases__, __base__, __mro__ magic methods.

Details

Improve this page