0

I am trying to acquire a basic understanding of python introspection and in doing so I found the in that regard useful mro() method mentioned here.

When I (as an introspection exercise) tried to use said method and the builtin dir() function in an attempt to find out where mro() might live, I however was unable to succeed. Why?

Here is my approach:

  • the mro() method obviously is available without any imports (unlike inspect.getmro() which is part of the inspect module; e.g. str.mro() returns [<class 'str'>, <class 'object'>]

  • Since str.mro() returns [<class 'str'>, <class 'object'>], the mro() method should live somewhere in str and/or object.

  • Yet neither dir(str) nor dir(object) appear to contain the mro() method. Also help() and help(str.mro) do not enlighten the puzzled student of introspection.

upgrd
  • 720
  • 7
  • 16

1 Answers1

1

If you look with dir(type) you'll find the magic method attribute __mro__. Quoted from here:

class.__mro__

This attribute is a tuple of classes that are considered when looking for base classes during method resolution.

class.mro()

This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in mro

Look at this answer for more about type which is the usual metaclass used in Python. Quoted from there:

type is the usual metaclass in Python. type is itself a class, and it is its own type. You won't be able to recreate something like type purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass type.

gstukelj
  • 2,291
  • 1
  • 7
  • 20