On this page
  1. Python Object, MRO & Initialization Dunder Flow
  2. Contents
  3. The object and type Root Hierarchy
  4. Method Resolution Order (MRO) & C3 Linearization
  5. Class Definition Dunder Flow
  6. Object Initialization Dunder Flow
  7. Post-Initialization Attribute Lookup & Finalization
  8. Complete Runnable Dunder Lifecycle Tracer

Python Object, MRO & Initialization Dunder Flow

Prev: Memory Management and Internals | Up: Advanced Python Internals | Next: Foreign Function Interfaces
Rel: Object-Oriented Programming (OOP), python metaprogramming, object, type, super, inspect, dataclasses
Ref: docs.python.org — Data Model | docs.python.org — C3 Method Resolution Order
Tags: #public #python3 #tutorials #internals #object #mro #dunder


Contents


The object and type Root Hierarchy

Everything in Python is an object, and every class is itself an instance of a metaclass (by default [[__builtins__/type|type]]). The root of the type system forms two intertwined relationships:

class Example:
    pass

assert Example.__bases__ == (object,)
assert issubclass(type, object)
assert isinstance(object, type)
assert isinstance(type, type)
assert isinstance(Example(), Example)
assert isinstance(Example, type)

Method Resolution Order (MRO) & C3 Linearization

When looking up an attribute or method on a class (or delegating via [[__builtins__/super|super()]]), Python searches classes in the deterministic linear sequence stored in cls.__mro__ (also returned as a list by cls.mro()).

Python computes MRO using the C3 Linearization algorithm, which guarantees:

  1. Subclasses appear before their base classes (monotonicity).
  2. Left-to-right base order declared in class Child(BaseA, BaseB): is preserved.
  3. Diamond bases are visited only once, after all subclasses that inherit from them.
  4. If no consistent linearization exists (e.g., class X(A, B) and class Y(B, A) combined in class Z(X, Y)), Python raises TypeError: Cannot create a consistent method resolution order (MRO) at class definition time.
class A:
    def trace(self) -> list[str]:
        return ["A"]

class B(A):
    def trace(self) -> list[str]:
        return ["B"] + super().trace()

class C(A):
    def trace(self) -> list[str]:
        return ["C"] + super().trace()

class D(B, C):
    def trace(self) -> list[str]:
        return ["D"] + super().trace()

print([cls.__name__ for cls in D.__mro__])  # ['D', 'B', 'C', 'A', 'object']
print(D().trace())                           # ['D', 'B', 'C', 'A']

Notice that inside B.trace(), super() does not call A.trace() directly — it dispatches to the next class in type(self).__mro__, which for an instance of D is C.


Class Definition Dunder Flow

Before any instance is ever constructed, executing a class statement triggers this exact sequence of hooks:

  1. Meta.__prepare__(name, bases, **kwds) — Returns the mapping (default dict) used as the class body namespace.
  2. Class body executes — Attributes, methods, and descriptors are populated into that namespace.
  3. Meta.__new__(mcls, name, bases, namespace, **kwds) — Allocates and creates the class object (type.__new__):
    • Computes C3 MRO (cls.__mro__).
    • Calls descriptor.__set_name__(cls, attr_name) on every descriptor attribute defined in the class body.
    • Calls super().__init_subclass__(**kwds) on the parent class so base classes can register or validate subclasses.
  4. Meta.__init__(cls, name, bases, namespace, **kwds) — Initializes the newly created class object.
  5. Class decorators (e.g., @dataclass) run bottom-to-top on the class object.

Object Initialization Dunder Flow

Every time you instantiate a class with obj = MyClass(*args, **kwargs), Python executes the following chain:

  1. type.__call__(MyClass, *args, **kwargs) (or a custom Meta.__call__) is invoked because calling a class invokes __call__ on its type (metaclass).
  2. MyClass.__new__(MyClass, *args, **kwargs) (resolved along MyClass.__mro__, ultimately reaching object.__new__):
    • Allocates and returns the new object instance.
    • Responsible for immutable type construction (int, str, tuple) or returning cached/singleton instances.
  3. Return-type check inside type.__call__:
    • If __new__ returned an object where isinstance(obj, MyClass) is True:
      • obj.__init__(*args, **kwargs) is called to populate instance state (must return None, otherwise TypeError is raised).
      • For [[stdlib_module/dataclasses|@dataclass]] classes, the generated __init__ then calls obj.__post_init__() at the end.
    • If __new__ returned an instance of a different type (or None), __init__ is skipped completely.
  4. type.__call__ returns obj to the caller.
MyClass(*args, **kwargs)
  └── Meta.__call__(MyClass, *args, **kwargs)        # default: type.__call__
        ├── obj = MyClass.__new__(MyClass, *args, **kwargs)
        │     └── ... MRO ... -> object.__new__(MyClass)
        └── if isinstance(obj, MyClass):
              └── obj.__init__(*args, **kwargs)      # must return None
                    └── [optional] obj.__post_init__()  # @dataclass hook
        └── return obj

Post-Initialization Attribute Lookup & Finalization

Once obj exists, attribute access and teardown follow their own dunder pipelines:


Complete Runnable Dunder Lifecycle Tracer

This pure-stdlib script traces every hook from class definition through MRO dispatch, instantiation, attribute access, and finalization:

class TracedDescriptor:
    def __set_name__(self, owner, name):
        self.name = name
        print(f"  [class-def] Descriptor.__set_name__({owner.__name__}, {name!r})")

    def __get__(self, instance, owner=None):
        if instance is None:
            return self
        print(f"  [access]    Descriptor.__get__({self.name!r})")
        return instance.__dict__.get(self.name)

    def __set__(self, instance, value):
        print(f"  [init/set]  Descriptor.__set__({self.name!r}, {value!r})")
        instance.__dict__[self.name] = value


class TracedMeta(type):
    @classmethod
    def __prepare__(mcls, name, bases, **kwds):
        print(f"1. Meta.__prepare__({name!r})")
        return super().__prepare__(name, bases, **kwds)

    def __new__(mcls, name, bases, namespace, **kwds):
        print(f"2. Meta.__new__({name!r})")
        return super().__new__(mcls, name, bases, namespace, **kwds)

    def __init__(cls, name, bases, namespace, **kwds):
        print(f"3. Meta.__init__({name!r}) | MRO={[c.__name__ for c in cls.__mro__]}")
        super().__init__(name, bases, namespace, **kwds)

    def __call__(cls, *args, **kwargs):
        print(f"4. Meta.__call__({cls.__name__}, args={args}, kwargs={kwargs})")
        return super().__call__(*args, **kwargs)


class Base(metaclass=TracedMeta):
    def __init_subclass__(cls, **kwds):
        super().__init_subclass__(**kwds)
        print(f"  [class-def] Base.__init_subclass__({cls.__name__})")


class Widget(Base):
    label = TracedDescriptor()

    def __new__(cls, *args, **kwargs):
        print(f"5. Widget.__new__({cls.__name__})")
        return super().__new__(cls)

    def __init__(self, label: str):
        print(f"6. Widget.__init__(label={label!r})")
        self.label = label

    def __del__(self):
        print("7. Widget.__del__()")


print("--- Instantiating Widget('button') ---")
w = Widget("button")
print("Reading w.label ->", w.label)
del w

Linked from

Related notes