Metaclass Magic & Class Creation Interception
Classes are objects, and their type is a metaclass (`type`). Subclassing `type` lets you intercept class definition at module load time via `__new__(mcs, name, bases, attrs)`. This enables auto-registering plugins, validating method signatures, and injecting class attributes 🧙♂️🏗️.
class PluginRegistryMeta(type):
registry = {}
def __new__(mcs, name, bases, namespace):
# Instantiate the class object:
cls = super().__new__(mcs, name, bases, namespace)
if bases: # Skip root base class
mcs.registry[name] = cls
return cls
class BasePlugin(metaclass=PluginRegistryMeta):
pass
class ImageCompressor(BasePlugin):
pass
class VideoTranscoder(BasePlugin):
pass
print(f"Registered Plugins: {list(PluginRegistryMeta.registry.keys())} 🚀")
# 82. Metaclass Magic & Class Creation Interception If you've used Django models, SQLAlchemy declarative bases, or Pydantic, you've used metaclasses. When you declare class fields, metaclasses inspect your class attributes before the class even finishes existing in memory 🛑. ```python # The Hierarchy of Types: # 42 is an instance of int. # "hello" is an instance of str. # int, str, and User are instances of TYPE (the default metaclass)! # type is an instance of ITSELF! ``` ### The Metaclass Creation Cycle 1. **`__prepare__(mcs, name, bases)`**: Returns a dictionary (or `OrderedDict`) to hold class namespace attributes while reading the class body. 2. **Body Execution**: Python runs the statements inside the `class` block, populating the namespace. 3. **`__new__(mcs, name, bases, namespace)`**: Allocates and returns the actual `PyTypeObject` representing the new class. Here you can mutate attributes, enforce abstract patterns, or register subclasses into global plugin maps. 4. **`__init__(cls, name, bases, namespace)`**: Initializes the already-created class object 🧙♂️🏗️. --- ### Interactive Pop-Quiz 🧠 #### When does a metaclass's __new__() method execute during the lifecycle of a Python application? - [ ] At module import time when the class block is parsed and evaluated by CPython 🏗️ - [ ] Only when an instance of the class is constructed with MyClass() - [ ] When the garbage collector sweeps unreferenced classes from memory - [ ] Only during automated test suite runs via pytest --- ### Practical Challenge 🎯 Implement a metaclass `RequireExecuteMeta(type)` that verifies every subclass (excluding classes where `bases` is empty) defines a callable method named `'execute'`. If missing, raise `TypeError("Missing required 'execute' method")`. Test defining a valid subclass with `execute()`, and verify a subclass without it raises `TypeError`. Print `'METACLASS_ENFORCED'`. <details> <summary>Solution</summary> ```python class RequireExecuteMeta(type): def __new__(mcs, name, bases, attrs): cls = super().__new__(mcs, name, bases, attrs) if bases: if "execute" not in attrs or not callable(attrs["execute"]): raise TypeError("Missing required 'execute' method") return cls class BaseTask(metaclass=RequireExecuteMeta): pass class ValidTask(BaseTask): def execute(self): return "OK" caught = False try: class InvalidTask(BaseTask): pass except TypeError: caught = True assert caught is True print("METACLASS_ENFORCED") ``` </details>