Python Metaclasses and Descriptors in Practice
Python exposes two hooks that live underneath ordinary class declarations. A metaclass decides what a class object becomes at the moment the class statement executes. A descriptor decides what happens when an attribute is read, assigned, or deleted on an instance. Django's ORM columns, SQLAlchemy's table definitions, Pydantic's fields, and pytest's fixture registry are all built on these hooks, which is why framework code often looks like magic until you have watched the machinery run once.
What You'll Learn
- 1Explain what happens between the class body and the finished class object
- 2Write a metaclass that collects subclasses into a registry automatically
- 3Implement the descriptor protocol with explicit storage and validation
- 4Choose between a metaclass and a descriptor before adding complexity
The class statement is a function call
When Python reaches a class statement it does three things in a fixed order. It executes the class body in a fresh namespace, it inspects the resulting namespace plus the bases to decide which metaclass to use, and then it calls that metaclass with the name, the base tuple, and the namespace. The object that comes back is an instance of the metaclass, not an instance of type alone. That is the entire trick: classes are objects, and objects are produced by calling something.
You can watch this directly. Passing metaclass=... in the class header does not change the body execution, it changes the final call. The body still runs top to bottom in its own dictionary, decorators still apply to names the body defines, and only afterwards does control pass to __new__ or __init__ on the metaclass. Because the namespace arrives as a plain dictionary, a metaclass can rename entries, wrap callables, drop keys, or register the finished class somewhere global before anyone imports it by hand.
Where the two hooks show up in real libraries
Once you can recognise the hooks, framework code stops looking ornamental. An ORM column is a descriptor: on the class it describes a typed, validated field, and on an instance it returns the value loaded from the row. A form field is the same idea with different bounds. A configuration object that recomputes an expensive value once and then serves it from the instance is a caching descriptor, and the fact that the second access is silent is precisely the point.
Metaclasses appear where a library needs to transform every class in a family at definition time. Registering command handlers, generating accessors from declared fields, validating that every subclass implements a required method, and attaching class-level metadata for an external tool are all jobs that must run exactly once, before anyone instantiates anything. The giveaway is that the behaviour cannot be expressed as a method you call, because there is no instance yet and no call site to invoke it from.
Neither hook belongs in ordinary application logic. If a plain method, a decorator, or a small base class does the job, that is the better answer: it keeps the class hierarchy ordinary, keeps debugging tools working without surprises, and leaves the heavy machinery available for the day the requirement genuinely calls for it.
Collecting subclasses without import side effects
The most honest reason to reach for a metaclass is automatic discovery. Consider a command-line tool where each subcommand lives in its own module. Asking every module to append itself to a list means one forgotten import silently removes a feature. A metaclass moves that bookkeeping to the moment a subclass is defined, so the registry is correct by construction.
class RegistryMeta(type):
_registry = {}
def __new__(mcls, name, bases, namespace):
cls = super().__new__(mcls, name, bases, namespace)
if bases:
mcls._registry[name] = cls
return cls
@classmethod
def all(mcls):
return dict(mcls._registry)
class Command(metaclass=RegistryMeta):
"""Base class; never registered itself."""
def run(self, argv):
raise NotImplementedError
class Greet(Command):
def run(self, argv):
return f"hello {argv[0]}"
class Sum(Command):
def run(self, argv):
return sum(int(a) for a in argv)
print(sorted(RegistryMeta.all())) # ['Greet', 'Sum']
Notice the if bases: guard. Without it the abstract base would register alongside concrete commands, and callers would instantiate a class that only raises. Registration happens at definition time, so importing a plugin file is enough to make it visible; no central module has to know the plugin list in advance.
The descriptor protocol, method by method
A descriptor is any object that defines at least one of __get__, __set__, or __delete__ and is stored on a class rather than an instance. Attribute lookup checks the instance dictionary first, then the class hierarchy, and only then falls back to normal attribute resolution. When the class lookup lands on a descriptor, Python calls its protocol method instead of returning the object itself.
| Hook | Called when | Typical use |
|---|---|---|
__get__(self, instance, owner) | Reading obj.attr or Cls.attr | Computed, cached, or logged values |
__set__(self, instance, value) | Assigning obj.attr = value | Validation, coercion, event notification |
__delete__(self, instance) | Deleting del obj.attr | Releasing resources, forbidden removal |
__set_name__(self, owner, name) | Once, at class creation | Capturing the attribute name automatically |
The owner argument is the class itself, which is how a descriptor can tell the difference between Product.price (useful for introspection) and product.price (useful for real data). Returning self when instance is None is the conventional way to support both.
Validated fields you declare once and reuse
With the protocol in hand, a reusable validated field becomes short. The descriptor stores its own name through __set_name__, keeps values in a per-instance underscore attribute, and rejects out-of-range input at assignment time rather than at some distant moment when a bad number is finally used.
class Ranged:
def __init__(self, low=None, high=None):
self.low = low
self.high = high
def __set_name__(self, owner, name):
self.name = name
self.storage = "_" + name
def __get__(self, instance, owner=None):
if instance is None:
return self
return getattr(instance, self.storage, None)
def __set__(self, instance, value):
if self.low is not None and value < self.low:
raise ValueError(f"{self.name} must be >= {self.low}")
if self.high is not None and value > self.high:
raise ValueError(f"{self.name} must be <= {self.high}")
setattr(instance, self.storage, value)
class Product:
price = Ranged(low=0)
stock = Ranged(low=0, high=1000)
def __init__(self, price, stock):
self.price = price
self.stock = stock
widget = Product(9.99, 40)
widget.stock = 5000 # raises ValueError: stock must be <= 1000
Because the descriptor lives on the class, every instance shares the validation logic while each keeps its own storage. Two fields can reuse the same class with different bounds, and a subclass inherits both the fields and the rules without copying a line.
Metaclass or descriptor: picking the smaller hammer
Both tools edit class behaviour, and both are easy to over-apply. The deciding question is whether the change concerns the class as an object or the attributes of instances.
| Situation | Prefer | Why |
|---|---|---|
| Registering, renaming, or wrapping classes at creation | Metaclass | Runs exactly once, at definition time |
| Validating, caching, or computing one attribute | Descriptor | Scoped to that attribute, inherited naturally |
| Applying the same change to many unrelated classes | Metaclass or decorator | Avoids repeating declarations |
| Needing the rule only on some instances of a class | Descriptor with a flag | Keeps per-object state in one place |
| Wanting readable, greppable class bodies | Plain attributes | Complexity should pay rent |
A metaclass is global across a class tree and fires during import, which makes it powerful and hard to debug. A descriptor is local to a name, easy to unit test in isolation, and composes with properties and __slots__. When both would work, the descriptor usually loses less of the language around it.
Inheritance, caching, and the edges that bite
Three edges are worth knowing before you ship. First, a metaclass must be a subclass of the metaclass of every base; combining a plain class with a metaclass-derived class raises a TypeError immediately. Second, a descriptor placed in an instance dictionary is never consulted, so a subclass that assigns self.price = 5 bypasses validation entirely unless the descriptor also implements __set__ on a class attribute the instance cannot shadow. Third, cached descriptors must decide what invalidates them: storing the computed value with setattr on the instance replaces the class-level lookup for that one object, which is exactly the caching trick, but it also means a later change to the underlying data will serve a stale result unless you clear it deliberately.
Common Mistakes
Registering the abstract base class along with real subclasses
Fix: Guard registration with a check on whether any bases exist, or test the class for abstract methods before adding it
Assuming an instance attribute assignment goes through the descriptor
Fix: Descriptors only intercept class-level attributes; validate assignment by defining __set__ and keeping the descriptor on the class
Reaching for a metaclass to add a helper method to every class
Fix: A class decorator or a shared base class does the same job with far less impact on debugging and introspection
Best Practices
- Keep descriptor storage in a private underscore attribute so normal instance dictionaries stay clean
- Give every metaclass a single, nameable responsibility such as registration or declaration collection
- Return self from __get__ when instance is None so introspection tools can still see the field definition
- Write a unit test for the metaclass in isolation before wiring it into a framework class
- Prefer __set_name__ over passing the attribute name as a string; it survives renaming automatically
Interview Questions
Q1: What is the difference between a metaclass and a base class?
A base class is what an instance is an instance of; a metaclass is what a class is an instance of. Base classes share behaviour among instances, metaclasses shape behaviour among classes at creation time.
Q2: When is a descriptor not used during attribute lookup?
When the name is found in the instance dictionary first, because instance attributes take precedence over class attributes for non-data descriptors. Defining __set__ makes it a data descriptor, which wins over the instance dictionary.
Q3: Why does __set_name__ exist?
Before it, descriptors had to be told their attribute name as a constructor argument, which broke as soon as the assignment target was renamed. Python now calls __set_name__ once on the descriptor during class creation with the owner and the name.
Key Takeaways
- A class statement executes its body, then calls the chosen metaclass with name, bases, and namespace
- Metaclasses are the right tool for work that must happen once when a class is defined, such as registration
- Descriptors intercept attribute reads, writes, and deletes, and they must live on the class to do so
- Data descriptors with __set__ outrank the instance dictionary; non-data descriptors lose to it
- When a metaclass and a descriptor both solve the problem, the descriptor keeps more of the language intact