Library

Volume 3 · Python Deep Dive

Notebook
Sign in

Section 9

Object-Oriented Python (MRO/C3 linearization, descriptors, __slots__, dataclasses, structural typing/Protocols)

1,065 words · about 5 min

9.1 Attribute Lookup & MRO

Attribute lookup for obj.attr walks: instance __dict__ → class __dict__ → base classes following the MRO → __getattr__ fallback → AttributeError.

Python resolves multiple inheritance with C3 linearization, guaranteeing children before parents, left-parent before right-parent, and each class appearing exactly once:

class A:
    def process(self): return "A"
class B(A):
    def process(self): return "B → " + super().process()
class C(A):
    def process(self): return "C → " + super().process()
class D(B, C):
    def process(self): return "D → " + super().process()

print(D.mro())          # [D, B, C, A, object]
print(D().process())    # "D → B → C → A"

Key insight: super() calls the next class in the MRO, not necessarily the immediate parent — this is what makes cooperative multiple inheritance and the diamond problem resolvable without calling a common ancestor twice.

9.2 Descriptors — The Engine Behind Properties

A descriptor implements any of __get__, __set__, __delete__. Data descriptors (define __get__ and __set__) take priority over instance __dict__; non-data descriptors (only __get__) do not — this is precisely how plain functions become bound methods.

class Validator:
    def __init__(self, min_val=None, max_val=None):
        self.min_val, self.max_val = min_val, max_val

    def __set_name__(self, owner, name):
        self.name = name
        self.private_name = f"_{name}"

    def __get__(self, obj, objtype=None):
        return self if obj is None else getattr(obj, self.private_name, None)

    def __set__(self, obj, value):
        if self.min_val is not None and value < self.min_val:
            raise ValueError(f"{self.name} must be >= {self.min_val}")
        setattr(obj, self.private_name, value)

class Product:
    price = Validator(min_val=0)
    quantity = Validator(min_val=0, max_val=10000)

    def __init__(self, name, price, quantity):
        self.name, self.price, self.quantity = name, price, quantity

p = Product("Widget", 9.99, 100)
# p.price = -5  # ValueError: price must be >= 0

@property, @classmethod, @staticmethod, and even ordinary methods (which bind self via __get__) are all implemented as descriptors under the hood.

9.3 __slots__ — Memory Optimization

class PointWithSlots:
    __slots__ = ('x', 'y')       # Fixed attribute set — no per-instance __dict__
    def __init__(self, x, y):
        self.x, self.y = x, y

Without __slots__, every instance carries a __dict__ (~100+ bytes overhead). With __slots__, attribute storage is fixed-size slots directly on the instance — roughly 60% memory savings for classes with many instances (>10K), at the cost of losing dynamic attribute assignment and needing __slots__ redeclared in every subclass.

9.4 Dataclasses

from dataclasses import dataclass, field, asdict

@dataclass
class Employee:
    name: str
    age: int
    department: str = "General"
    skills: list[str] = field(default_factory=list)  # mutable default handled safely

    def __post_init__(self):
        if self.age < 0:
            raise ValueError("Age cannot be negative")

@dataclass(frozen=True)
class Coordinate:
    x: float
    y: float
    # frozen=True → immutable AND hashable → usable as dict key

@dataclass(order=True)
class Priority:
    level: int
    name: str
    # __lt__, __le__, __gt__, __ge__ auto-generated, compares by (level, name)

@dataclass auto-generates __init__, __repr__, __eq__ (and optionally ordering/hashing), eliminating the boilerplate of a hand-written value class while remaining a full, inheritable class (unlike NamedTuple, which is tuple-based and more restrictive).

9.5 Protocols & Structural Subtyping

from typing import Protocol, runtime_checkable

@runtime_checkable
class Drawable(Protocol):
    def draw(self) -> str: ...

class Circle:
    def draw(self) -> str: return "Drawing circle"

def render(shape: Drawable) -> None:
    print(shape.draw())

render(Circle())                      # Works — no inheritance required
print(isinstance(Circle(), Drawable))  # True — structural check at runtime

Protocols formalize duck typing with static type checking: any class with a matching method signature satisfies the protocol without explicit inheritance (structural subtyping), as opposed to ABCs, which require explicit inheritance or registration (nominal subtyping). Use Protocols when you don’t control the classes you want to accept.

Interview Q&A — Section 9

Q1: Explain MRO with an example where it actually matters.

A: In class D(B, C) where both B and C inherit from A, C3 linearization produces [D, B, C, A, object]. If each override calls super(), B’s super() resolves to C (the next class in the MRO), not directly to A — this ensures A’s method runs exactly once even though it’s reachable through two inheritance paths, which is exactly what prevents the classic diamond-problem double-invocation bug.

Q2: How do descriptors work, and where does Python use them internally?

A: A descriptor is any object implementing __get__, __set__, or __delete__, controlling attribute access at the class level. Data descriptors (both __get__ and __set__) take priority over an instance’s __dict__; non-data descriptors (only __get__) do not. Python uses descriptors internally for @property (data descriptor), @classmethod/@staticmethod (non-data descriptors), and — critically — for functions themselves, which is the mechanism that automatically binds self when you access a method through an instance.

Q3: When would you use __slots__, and what do you give up?

A: When creating a very large number of instances (tens of thousands or more) of a class with a fixed, known set of attributes — common in data processing and high-throughput services — __slots__ cuts per-instance memory by roughly 60% by replacing the per-instance __dict__ with fixed slots. The tradeoffs: no dynamic attribute addition, no __weakref__ unless explicitly added to slots, and every subclass in the hierarchy must also declare __slots__ or the memory benefit is lost.

Q4: What’s the difference between a Protocol and an ABC, and when do you reach for each?

A: An ABC requires explicit inheritance (or .register()) — nominal subtyping; you control the class hierarchy. A Protocol checks structurally — any class with matching method signatures satisfies it, no inheritance needed. Use Protocols when accepting third-party or legacy classes you don’t control (they just need the right shape); use ABCs when you own the hierarchy and want to enforce a contract (@abstractmethod) plus share concrete behavior across subclasses.