Python Masterclass / Module 7 of 10 Phase 3: Advanced Python & Concurrency Architecture

Advanced OOP, The Python Data Model (Dunders), C3 MRO, Descriptors & Metaclasses

28 min study + 2 Live Wasm Labs
⚡ Answer-First Executive Summary (TL;DR) Module 7 Key Takeaways
  • ✓ __new__(cls, ...) is the static constructor that allocates and returns the new instance (essential when subclassing immutable types like int, str, tuple or implementing singletons); __init__(self, ...) initializes attributes on the already-allocated instance.
  • ✓ The Descriptor Protocol (__get__, __set__, __delete__, __set_name__) is the engine behind Python’s object model: functions become bound methods, @property intercepts attribute access, and SQLAlchemy/Django/Pydantic fields validate data via descriptors.
  • ✓ Exact attribute lookup order for obj.attr: (1) Data Descriptor on type(obj).__mro__ → (2) obj.__dict__["attr"] → (3) Non-Data Descriptor / method on type(obj).__mro__ → (4) __getattr__ fallback.
  • ✓ Prefer __init_subclass__ (PEP 487) or class decorators over custom Metaclasses for 95% of plugin registration and class validation tasks.

01. The Descriptor Protocol & Exact object.__getattribute__ Lookup Chain

Every time you evaluate obj.attr in Python, object.__getattribute__(obj, "attr") executes a strict 5-step lookup algorithm in C (Objects/object.c: _PyObject_GenericGetAttrWithDict). Knowing this chain is the key to understanding how methods bind self, how @cached_property works, and how ORMs validate fields:

Evaluating: obj.attr   (where cls = type(obj))
  │
  ├─▶ STEP 1: Search cls.__mro__ for 'attr'. Is it a DATA DESCRIPTOR (defines __get__ AND __set__/__delete__)?
  │     └── YES ──▶ Return cls_attr.__get__(obj, cls)   [Overrides obj.__dict__! e.g. @property with setter]
  │
  ├─▶ STEP 2: Look in Instance Dictionary: Is 'attr' in obj.__dict__ (or instance __slots__)?
  │     └── YES ──▶ Return obj.__dict__['attr']         [e.g. regular attributes & @cached_property values]
  │
  ├─▶ STEP 3: Was 'attr' found on cls.__mro__ as a NON-DATA DESCRIPTOR (defines ONLY __get__)?
  │     └── YES ──▶ Return cls_attr.__get__(obj, cls)   [e.g. functions bind into BoundMethod(fn, obj)!]
  │
  ├─▶ STEP 4: Was 'attr' found on cls.__mro__ as a plain class variable?
  │     └── YES ──▶ Return cls_attr
  │
  └─▶ STEP 5: Does cls define __getattr__(self, "attr")?
        ├── YES ──▶ Call and return obj.__getattr__("attr")
        └── NO  ──▶ Raise AttributeError

02. The Python Data Model ("Dunder") Reference Matrix

Table 7.1 — Essential Python Data Model Special Methods & CType Slots
Category Special Methods Triggered By Staff Engineering Rule / Invariant
Lifecycle __new__, __init__ MyClass(*args) __new__ allocates and returns the instance; __init__ configures it and must return None.
Representation __repr__, __str__, __format__ repr(x), print(x), f"{x:spec}" Always implement __repr__ for unambiguous debugging logs; __str__ falls back to __repr__ automatically.
Equality & Hash __eq__, __hash__, __lt__ x == y, hash(x), sorted() Return NotImplemented (not False) from __eq__ for unknown types so Python can try the reflected comparison.
Descriptors __set_name__, __get__, __set__ Class creation & obj.attr __set_name__(self, owner, name) (PEP 487) automatically informs a descriptor of its attribute name at class creation time.
Class Hooks __init_subclass__, __class_getitem__ class Sub(Base, **kw): Use __init_subclass__ to auto-register plugins or enforce subclass contracts without writing a custom metaclass.
Containers & Slicing __len__, __getitem__, __setitem__, __missing__, __contains__ len(c), c[k], k in c Subclassing dict and defining __missing__(self, key) intercepts missing keys cleanly (how collections.defaultdict works).
Operators & Callables __call__, __add__, __radd__, __iadd__, __matmul__, __bool__ obj(), a + b, a += b, A @ B If a.__add__(b) returns NotImplemented, Python automatically dispatches reflected b.__radd__(a).
Copying, Pickling & Buffers __copy__, __deepcopy__, __reduce__, __buffer__ (PEP 688) copy.deepcopy(x), memoryview(x) Controls deep cloning memoization, multiprocessing IPC serialization, and zero-copy buffer exposure.

03. Modern @dataclass Mechanics, enum.StrEnum / Flag & Abstract Base Classes (abc.ABC)

Python 3.10–3.14 provides declarative class builders that eliminate boilerplate while enforcing runtime invariants:

@dataclass(slots=True, frozen=True, kw_only=True)

Synthesizes __init__, __repr__, __eq__, and __hash__ (when frozen=True), packs fields into __slots__, uses field(default_factory=list) for safe mutable defaults, and runs __post_init__ for cross-field validation.

enum.StrEnum, IntFlag & @verify

StrEnum (Python 3.11+) serializes directly as a JSON string without .value unwrapping; Flag / IntFlag provide type-safe bitwise permission masks ( Perm.READ | Perm.WRITE).

abc.ABC & @abstractmethod

Backed by ABCMeta: prevents instantiating any subclass at runtime until every @abstractmethod is implemented, and supports MyABC.register(ThirdPartyClass) virtual subclassing.

💻 Hands-On WebAssembly Python Labs (Module 7)

Click Run & Edit Live (Wasm) on any lab below to execute and modify the code in our browser Pyodide runtime.

▶ Interactive Wasm Lab

Lab 7.1: Building a Zero-Dependency Schema Validator Using __set_name__ Data Descriptors

See how Django ORM, SQLAlchemy, and Pydantic work under the hood by building a reusable BoundedNumber Data Descriptor and a non-data @cached_property.

class BoundedNumber:
    """A Data Descriptor that validates type and min/max bounds on every assignment."""
    def __init__(self, *, min_val: float, max_val: float):
        self.min_val = min_val
        self.max_val = max_val
        self.private_name = ""

    def __set_name__(self, owner: type, name: str) -> None:
        # Automatically called by type.__new__ when the class body finishes executing!
        self.public_name = name
        self.private_name = f"_{name}"

    def __get__(self, instance: object, owner: type | None = None):
        if instance is None:
            return self
        return getattr(instance, self.private_name)

    def __set__(self, instance: object, value: float | int) -> None:
        if not isinstance(value, (int, float)):
            raise TypeError(f"{self.public_name} must be numeric, got {type(value).__name__}")
        if not (self.min_val <= value <= self.max_val):
            raise ValueError(f"{self.public_name}={value} violates bounds [{self.min_val}, {self.max_val}]")
        setattr(instance, self.private_name, float(value))

class ModelInferenceConfig:
    temperature = BoundedNumber(min_val=0.0, max_val=2.0)
    top_p = BoundedNumber(min_val=0.01, max_val=1.0)

    def __init__(self, temperature: float, top_p: float):
        self.temperature = temperature  # Triggers BoundedNumber.__set__!
        self.top_p = top_p

cfg = ModelInferenceConfig(temperature=0.7, top_p=0.95)
print("[1] Validated Descriptor Instance:", cfg.__dict__)

try:
    cfg.temperature = 3.5
except ValueError as err:
    print("[2] Descriptor Caught Invalid Mutation:", err)
▶ Interactive Wasm Lab

Lab 7.2: Auto-Registering Agent Tool Plugins (__init_subclass__) & C3 MRO Inspection

Build an automatic plugin registry using PEP 487 __init_subclass__ and inspect cooperative multiple inheritance across a diamond hierarchy.

# 1. Auto-Registering Plugin Architecture via __init_subclass__ (Zero Metaclass boilerplate!)
class AgentToolPlugin:
    _registry: dict[str, type["AgentToolPlugin"]] = {}

    def __init_subclass__(cls, *, tool_id: str | None = None, **kwargs):
        super().__init_subclass__(**kwargs)
        key = tool_id or cls.__name__.lower()
        if not hasattr(cls, "execute"):
            raise TypeError(f"Plugin {cls.__name__} must implement an execute() method")
        AgentToolPlugin._registry[key] = cls

class WebSearchPlugin(AgentToolPlugin, tool_id="web_search"):
    def execute(self) -> str:
        return "Searching live web index..."

class CodeSandboxPlugin(AgentToolPlugin, tool_id="python_wasm"):
    def execute(self) -> str:
        return "Executing isolated Pyodide sandbox..."

print("[1] Auto-Discovered Plugin Registry:", list(AgentToolPlugin._registry.keys()))
for tid, plugin_cls in AgentToolPlugin._registry.items():
    print(f"    • {tid:<12} -> {plugin_cls().execute()}")

# 2. Cooperative Multiple Inheritance & C3 Linearization (__mro__)
class BaseHandler:
    def handle(self) -> list[str]:
        return ["BaseHandler"]

class AuthMixin(BaseHandler):
    def handle(self) -> list[str]:
        return ["AuthMixin"] + super().handle()

class RateLimitMixin(BaseHandler):
    def handle(self) -> list[str]:
        return ["RateLimitMixin"] + super().handle()

class ProductionGateway(AuthMixin, RateLimitMixin):
    def handle(self) -> list[str]:
        return ["ProductionGateway"] + super().handle()

gw = ProductionGateway()
print("\n[2] C3 Linearization MRO:", [c.__name__ for c in ProductionGateway.__mro__])
print("    Cooperative super() Chain:", " -> ".join(gw.handle()))

Frequently Asked Staff Interview Questions (Module 7)

What is the exact difference between a Data Descriptor and a Non-Data Descriptor? ▸

A Data Descriptor defines both __get__ and __set__ (or __delete__), like @property with a setter or an ORM validated field—it takes precedence OVER an entry of the same name in the instance’s __dict__. A Non-Data Descriptor defines ONLY __get__ (like standard methods or @functools.cached_property)—an entry in the instance’s __dict__ shadows a non-data descriptor!

Why does defining __eq__ on a class make its instances unhashable (TypeError: unhashable type)? ▸

The hash invariant requires that if a == b, then hash(a) == hash(b). If you override __eq__ to compare attributes without overriding __hash__, two equal instances would inherit object.__hash__ (which hashes memory addresses) and produce different hashes, corrupting dict/set lookups. Therefore, CPython automatically sets __hash__ = None whenever you define __eq__ without __hash__.

How does Python’s C3 Linearization Method Resolution Order (MRO) work with super()? ▸

C3 Linearization computes a deterministic topological ordering of a class hierarchy (cls.__mro__) that preserves local precedence order and monotonicity. Calling super().method() does NOT mean "call my parent class"—it means "call the next class after me in self.__class__.__mro__," enabling cooperative multiple inheritance across diamond hierarchies.