Library

Volume 3 · Python Deep Dive

Notebook
Sign in

Section 15

Advanced Patterns & Metaprogramming (metaclasses, descriptors deep dive, ABCs, monkey patching, decorators with arguments)

1,234 words · about 6 min

15.1 Metaclasses

class MyClass: pass
print(type(MyClass))     # <class 'type'> — MyClass is an instance of type
print(type(type))        # <class 'type'> — type is its own metaclass

# type(name, bases, namespace) creates classes dynamically
DynamicClass = type('DynamicClass', (object,), {'__init__': lambda self, name: setattr(self, 'name', name)})

class ValidatedMeta(type):
    def __new__(mcs, name, bases, namespace):
        for attr_name, attr_value in namespace.items():
            if callable(attr_value) and not attr_name.startswith('_') and not attr_value.__doc__:
                raise TypeError(f"Method '{attr_name}' in '{name}' must have a docstring")
        return super().__new__(mcs, name, bases, namespace)

class Plugin(metaclass=ValidatedMeta):
    def execute(self):
        """Execute the plugin."""  # required by the metaclass

A metaclass is “the class of a class” — it controls the class-creation process itself (can validate, modify, or reject a class definition before it even exists). __init_subclass__ (3.6+) is the modern, simpler alternative for the most common use case — automatic subclass registration/validation — without the ceremony of a full metaclass:

class PluginBase:
    _registry = {}
    def __init_subclass__(cls, plugin_name=None, **kwargs):
        super().__init_subclass__(**kwargs)
        cls._registry[plugin_name or cls.__name__] = cls

class EmailPlugin(PluginBase, plugin_name="email"): pass

15.2 Descriptors Deep Dive

class TypeChecked:
    def __init__(self, expected_type): self.expected_type = expected_type
    def __set_name__(self, owner, name):
        self.name, self.private_name = name, f"_{name}"
    def __get__(self, obj, objtype=None):
        return self if obj is None else getattr(obj, self.private_name)
    def __set__(self, obj, value):
        if not isinstance(value, self.expected_type):
            raise TypeError(f"{self.name} must be {self.expected_type.__name__}")
        setattr(obj, self.private_name, value)

class Order:
    customer = TypeChecked(str)

Attribute lookup priority: data descriptor on the type → instance __dict__ → non-data descriptor on the type → __getattr__ fallback → AttributeError. This ordering is why @property (a data descriptor) always wins over an accidental same-named instance attribute, while a plain method (non-data descriptor) can be shadowed by an instance attribute of the same name.

15.3 __getattr__ vs __getattribute__

class LazyLoader:
    def __getattr__(self, name):
        """Called ONLY when normal lookup fails — safe, low overhead."""
        value = f"loaded_{name}"
        setattr(self, name, value)   # cache for next access
        return value

class LoggingProxy:
    def __getattribute__(self, name):
        """Called on EVERY attribute access — must special-case internal names
        to avoid infinite recursion."""
        if name == '_wrapped':
            return object.__getattribute__(self, name)
        print(f"Accessing: {name}")
        return getattr(object.__getattribute__(self, '_wrapped'), name)

15.4 ABCs & Virtual Subclasses

from abc import ABC, abstractmethod
import collections.abc

class MyMapping:
    def __getitem__(self, key): return self._data[key]
    def __len__(self): return len(self._data)
    def __iter__(self): return iter(self._data)

collections.abc.Mapping.register(MyMapping)     # virtual subclass, no inheritance needed
isinstance(MyMapping(), collections.abc.Mapping) # True

15.5 Design Patterns, Pythonically

# Factory — a dict of constructors is often enough, no need for a class hierarchy
_creators = {"email": EmailNotification, "sms": SMSNotification}
def create(kind): return _creators[kind]()

# Strategy — just pass a function
class DataProcessor:
    def __init__(self, strategy): self.strategy = strategy
    def process(self, data): return self.strategy(data)

# Observer — events as a dict of lists of callables
class EventSystem:
    def __init__(self): self._handlers = {}
    def on(self, event, handler): self._handlers.setdefault(event, []).append(handler)
    def emit(self, event, *a, **kw):
        for h in self._handlers.get(event, []): h(*a, **kw)

Python’s first-class functions, duck typing, and dynamic nature often make classic GoF patterns lighter-weight than their Java/C++ equivalents — factories can be dicts, strategies can be plain functions, singletons can be modules.

15.6 Monkey Patching

import datetime
original_now = datetime.datetime.now
datetime.datetime.now = lambda: datetime.datetime(2026, 1, 1, 12, 0)   # patch
datetime.datetime.now = original_now                                    # restore

# Prefer unittest.mock.patch for anything test-related — auto-restores on exit
from unittest.mock import patch
with patch('datetime.datetime') as mock_dt:
    mock_dt.now.return_value = datetime.datetime(2026, 1, 1)

Acceptable for testing (mocking external dependencies) or temporary hotfixes; dangerous in production code because it silently breaks assumptions other code may rely on, and is hard to trace/debug.

15.7 Decorators With Arguments (recap in metaprogramming context)

def decorator_with_args(arg1, arg2):        # Step 1: called with the decorator's own args
    def actual_decorator(func):              # Step 2: called with the function
        @functools.wraps(func)
        def wrapper(*args, **kwargs):        # Step 3: called with the function's args
            print(f"Args: {arg1}, {arg2}")
            return func(*args, **kwargs)
        return wrapper
    return actual_decorator

Interview Q&A — Section 15

Q1: What is a metaclass, and when would you actually reach for one over alternatives?

A: A metaclass is the class of a class — it controls how a class object itself is created, letting you validate or transform the class namespace before the class even exists. I reach for one when I need to intervene during class creation — enforcing conventions across an entire hierarchy, or building something like an ORM’s declarative base. For the much more common case of “automatically register every subclass” or “validate subclass definitions,” __init_subclass__ (since 3.6) achieves the same result with far less ceremony and is the modern default choice.

Q2: Explain the full attribute lookup chain in Python, including descriptors.

A: Accessing obj.attr always goes through type(obj).__getattribute__, which checks, in order: a data descriptor (__get__ and __set__) on the type/MRO, then the instance’s own __dict__, then a non-data descriptor (__get__ only) on the type/MRO, then falls back to __getattr__ if defined, and finally raises AttributeError. This ordering is exactly why @property (a data descriptor) always overrides an instance attribute of the same name, while an ordinary method (non-data descriptor) can be shadowed by one.

Q3: What’s the difference between a class decorator and a metaclass?

A: A class decorator runs after the class object already exists — it can wrap or replace methods, add attributes, but cannot prevent creation or intercept the raw namespace before the class is built, and it must be reapplied to every subclass explicitly. A metaclass controls the creation process itself — it sees the namespace before the class exists, can reject or transform it in __new__, and its behavior is automatically inherited by every subclass. Prefer decorators for straightforward post-creation enhancements; reserve metaclasses for cases that genuinely need to control the creation process or need that automatic-inheritance behavior.

Q4: When is monkey patching acceptable, and what’s the safer alternative in test code?

A: It’s reasonable for testing (mocking external dependencies you don’t control) or as a very temporary production hotfix. It’s dangerous as a permanent production technique because it silently changes behavior other code may depend on and is hard to trace during debugging. In tests, prefer unittest.mock.patch as a context manager or decorator over manually reassigning attributes — it automatically restores the original object when the with block or test exits, so a failing assertion mid-test can’t leave the patch applied and contaminate subsequent tests.