Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this an ambiguous MRO?

Tags:

class First(object):
    def __init__(self):
        print("first")

class Second(First):
    def __init__(self):
        print("second")

class Third(First, Second):
    def __init__(self):
        print("third")

Source

Why can't Python create a consistent MRO? It seems to me it's pretty clear:

  1. Search in First if method does not exist in Third
  2. Search in Second if method does not exist in First

But if you try it out:

TypeError: Error when calling the metaclass bases
    Cannot create a consistent method resolution
order (MRO) for bases First, Second
like image 613
Derek 朕會功夫 Avatar asked Dec 14 '17 08:12

Derek 朕會功夫


People also ask

What is MRO method resolution order?

The Method Resolution Order (MRO) is the set of rules that construct the linearization. In the Python literature, the idiom "the MRO of C" is also used as a synonymous for the linearization of the class C.

What is MRO in OOP concept of Python?

Method Resolution Order(MRO) it denotes the way a programming language resolves a method or attribute. Python supports classes inheriting from other classes. The class being inherited is called the Parent or Superclass, while the class that inherits is called the Child or Subclass.

How do you fetch the MRO of an object class in Python?

To get the MRO of a class, you can use either the __mro__ attribute or the mro() method. The __mro__ attribute returns a tuple, but the mro() method returns a python list.


2 Answers

To be "consistent" the MRO should satisfy these constraints:

  1. If a class inherits from multiple superclasses, the ones it lists earlier in the superclass list should come earlier in the MRO than the ones it lists later.
  2. Every class in the MRO should come before any of its superclasses.

Your proposed hierarchy does not have any possible ordering meeting these constraints. Because Third is defined to inherit from First before Second, First should come before Second in the MRO. But because Second inherits from First, Second should come before First in the MRO. This contradiction cannot be reconciled.

You can read more about the precise method Python uses to compute the MRO, which is called the C3 linearization algorithm.

like image 73
BrenBarn Avatar answered Sep 18 '22 12:09

BrenBarn


Python internally thinks not to have super class before sub-class.

According to your code. After Scanning or loading the classes, Python thinks the method resolution has to be:

Third -> Second -> First

Here, First is the super class of Second.

But while executing, after checking Third it confronts First which is the super class of Second.

Hence the TypeError.

class Third(First, Second): # Wrong
class Third(Second, First): # Correct
like image 27
Sai Kiran Avatar answered Sep 20 '22 12:09

Sai Kiran