On this page
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
- > Method Resolution Order (MRO) & C3 Linearization
- > Class Definition Dunder Flow
- > Object Initialization Dunder Flow
- > Post-Initialization Attribute Lookup & Finalization
- > Complete Runnable Dunder Lifecycle Tracer
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:
- Inheritance (
issubclass): Every class — includingtypeitself — inherits from[[__builtins__/object|object]].object.__bases__is(). - Instantiation (
isinstance): Every class — includingobjectandtypeitself — is an instance oftype.
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:
- Subclasses appear before their base classes (monotonicity).
- Left-to-right base order declared in
class Child(BaseA, BaseB):is preserved. - Diamond bases are visited only once, after all subclasses that inherit from them.
- If no consistent linearization exists (e.g.,
class X(A, B)andclass Y(B, A)combined inclass Z(X, Y)), Python raisesTypeError: 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:
Meta.__prepare__(name, bases, **kwds)— Returns the mapping (defaultdict) used as the class body namespace.- Class body executes — Attributes, methods, and descriptors are populated into that namespace.
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.
- Computes C3 MRO (
Meta.__init__(cls, name, bases, namespace, **kwds)— Initializes the newly created class object.- 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:
type.__call__(MyClass, *args, **kwargs)(or a customMeta.__call__) is invoked because calling a class invokes__call__on its type (metaclass).MyClass.__new__(MyClass, *args, **kwargs)(resolved alongMyClass.__mro__, ultimately reachingobject.__new__):- Allocates and returns the new object instance.
- Responsible for immutable type construction (
int,str,tuple) or returning cached/singleton instances.
- Return-type check inside
type.__call__:- If
__new__returned an object whereisinstance(obj, MyClass)isTrue:obj.__init__(*args, **kwargs)is called to populate instance state (must returnNone, otherwiseTypeErroris raised).- For
[[stdlib_module/dataclasses|@dataclass]]classes, the generated__init__then callsobj.__post_init__()at the end.
- If
__new__returned an instance of a different type (orNone),__init__is skipped completely.
- If
type.__call__returnsobjto 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:
- Attribute read (
obj.attr):obj.__getattribute__("attr")is always called first.- Checks data descriptors (defining
__set__or__delete__) ontype(obj).__mro__-> callsdesc.__get__(obj, type(obj)). - Checks instance storage (
obj.__dict__["attr"]or__slots__). - Checks non-data descriptors (e.g., methods defining only
__get__) and class attributes ontype(obj).__mro__. - Only if all of the above fail with
AttributeError, callsobj.__getattr__("attr").
- Attribute write (
obj.attr = val): callsobj.__setattr__("attr", val)(which checks data descriptor__set__before writing toobj.__dict__). - Finalization: when reference count drops to zero (or cyclic GC reclaims
obj), Python callsobj.__del__()if defined.
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
- tuts/javascript/tutorials/prototype_chain_and_new_flow
- tuts/programming/paradigms/object_oriented_programming
- tuts/python3
- tuts/python3/__builtins__/object
- tuts/python3/__builtins__/super
- tuts/python3/__builtins__/type
- tuts/python3/python metaprogramming
- tuts/python3/tutorials
- tuts/python3/tutorials/advanced_python_internals
- tuts/python3/tutorials/advanced_python_internals/foreign_function_interfaces
- tuts/python3/tutorials/advanced_python_internals/memory_management_and_internals
- tuts/python3/tutorials/advanced_python_internals/python_object_mro_and_initialization
- tuts/python3/tutorials/intermediate_python_and_software_engineering/object_oriented_programming
Related notes
- tuts/python3/tutorials/advanced_python_internals Linked here; links to this page; shared tags: #internals, #tutorials
- tuts/python3/tutorials/advanced_python_internals/foreign_function_interfaces Linked here; links to this page; shared tags: #internals, #tutorials
- tuts/python3/tutorials/advanced_python_internals/memory_management_and_internals Linked here; links to this page; shared tags: #internals, #tutorials
- tuts/python3/tutorials/intermediate_python_and_software_engineering/object_oriented_programming Linked here; links to this page; shared tags: #tutorials
- tuts/python3/__builtins__/object Linked here; links to this page
- tuts/python3/__builtins__/super Linked here; links to this page
- tuts/python3/__builtins__/type Linked here; links to this page
- tuts/python3/python metaprogramming Linked here; links to this page
- tuts/javascript/tutorials/prototype_chain_and_new_flow links to this page; shared tags: #internals, #tutorials
- tuts/python3/tutorials links to this page; shared tags: #tutorials