Lesson · Advanced Object Model
Metaclasses
75 min readMetaclasses
A metaclass customizes class creation in the same way a class customizes instance creation. It is powerful but global in effect, so class decorators or `__init_subclass__` are often simpler choices.
Learning goals
- Explain why calling
typeon a class reports its metaclass, and when that metaclass is a subclass rather thantypeitself. - Write a metaclass
__new__that registers each class created through the hierarchy, including subclasses that never mention the metaclass. - Say what
mcls,name,bases, andnamespacecontain at each step of class creation. - Compare a metaclass with a class decorator and
__init_subclass__for a registration task. - Trace what happens when two bases demand incompatible metaclasses.
Mental model
The loop repeats for every subclass, which is why a registry fills itself with no extra calls. Each entry stores the class object that the super call returned, not the name string the hook received.
Mental model
read it top to bottom
class Plugin(metaclass=Registered): Registered.__new__ runs ↓ class object returned, itself an instance of Registered ↓ class CsvPlugin(Plugin): metaclass inherited, __new__ runs again
Core idea
A metaclass is the type of a class: it decides what happens when the class object is built, just as a class decides what happens when an instance is built. Subclassing type puts a hook around creation, and __new__ receives the captured namespace before the class exists. One definition then affects every class in that hierarchy, which is the power and the cost in the same sentence.
type as metaclass
Every class is an instance of its metaclass, and type is the default one: type(Example) reports type itself unless a type subclass was involved. The three-argument form type(name, bases, namespace) performs the same creation the class statement performs, which is why a custom metaclass only has to override __new__ and delegate to super().
Custom metaclasses
A custom metaclass can intercept class creation, transform the namespace, register classes, or enforce constraints. The behavior affects every class using that metaclass hierarchy.
__new__
__new__ creates and returns the new instance before __init__ initializes it. It matters most for immutable subclasses, custom allocation, and metaclass-driven construction.
__init__
__init__ configures an already-created instance and must return None. Validation can happen here when an invalid object should never finish initialization.
Class customization
A metaclass can read or edit the namespace before the class object is finalized: add helper methods, rename attributes, or raise an error when a convention is violated. Because the hook runs for every class built through the metaclass, one definition changes behavior across the whole hierarchy, for better or worse.
Prefer simpler alternatives when possible
A metaclass is rarely the first tool to reach for: it affects every class in its hierarchy and conflicts with other metaclasses, which is why frameworks reserve it for customizing the class object itself. For registration or validation, __init_subclass__ or a class decorator usually expresses the same rule with less reach, so switch to a metaclass only when those hooks cannot do the job.
Walkthrough
class Plugin(metaclass=Registered)sendsPluginitself throughRegistered.__new__; the guardif name != "Plugin"returns the class without storing it, so the base stays out of the registry.class CsvPlugin(Plugin)never mentions the metaclass, but it inheritsRegisteredfromPlugin, so__new__fires again withname="CsvPlugin"and the guard lets it register.cls = super().__new__(mcls, name, bases, namespace)builds the class before the registration line runs; storingclsrather thannamemakesRegistered.registrymap strings to live class objects.- Predict before running: the exact contents of
Registered.registryafter both definitions, and what a further subclass ofCsvPluginwould add to it.
Experiments to try
- Add another subclass,
class JsonPlugin(Plugin): pass, and confirm the registry grows without any explicit registration call. - Move the registry insert above
super().__new__and try to referencecls; read theUnboundLocalErrorand explain why the class object cannot exist yet. - Remove the guard so
"Plugin"registers too, and connect the extra entry to the moment the base class was created. - Define a second metaclass
Named(type)with its own__new__and buildclass Broken(Plugin, metaclass=Named); read theTypeErrorabout a metaclass conflict and say which two metaclasses could not be combined.
Common mistakes
- Registering
nameinstead ofcls: the registry then maps to a string, and every later lookup fails at attribute access rather than at registration. - Forgetting that subclasses inherit the metaclass:
CsvPlugin(Plugin)getsRegisteredbehavior implicitly, which is the point for a registry but surprising for a hook meant for one class. - Storing a class before
super().__new__returns: the class object does not exist yet, so the reference is unbound and the insert cannot run. - Combining bases with incompatible metaclasses: Python raises
TypeErrorat the class statement because it will not guess which metaclass should win.
Practice: Easy
- Run the worked example and name the two classes that reach the registry check; then explain why
PluginandCsvPluginend up on different sides of the guard. - Add
class JsonPlugin(Plugin): passand predict the registry keys before rerunning; the key comes from the class name string, not the variable you assign it to. - Create one class with and one class without
metaclass=Registeredand printtype(cls)for each; identify which result istypeand which isRegistered.
Practice: Medium
- Change the registry to store classes in categories: read a
categoryattribute from the namespace and group entries in a nested dictionary; register two subclasses in different categories and verify the result. - Add validation that raises
TypeErrorunless the namespace defines arunmethod; write one compliant subclass and one that fails, and note when each error appears. - Replace the metaclass with a class decorator that performs the same insert; compare when each runs, with the metaclass during creation and the decorator handling the finished class object.
Practice: Hard
- Build a registry that validates entries: classes must define
run, duplicatenamevalues raise at creation, andlookup(name)returns the class or raisesKeyError; write the error contract down before implementing. - Set up a failure lab with three broken creations: a registry that stores
name, a metaclass conflict, and an insert that referencesclsbefore assignment; explain each symptom from the creation steps. - Implement the same registry with
__init_subclass__instead of a metaclass, then state one change that only the metaclass version can make, such as replacing the class object, and why the hook version is still easier to read.
Lesson checklist
- I can explain why a class statement triggers a metaclass
__new__call and what that call receives. - I can write a registry metaclass and say which classes it captures, including subclasses that never mention it.
- I can name two situations where a class decorator or
__init_subclass__is the better tool. - I can read a metaclass conflict
TypeErrorand identify the two metaclasses involved.
Remember
A metaclass is the type of a class, and its `__new__` is where class creation can be observed or adjusted: it receives the name, the bases, and the namespace, and it must return the class object. Registries, validation, and namespace edits all fit in that one hook, but its reach covers an entire hierarchy, so simpler hooks win whenever they can.
Interview angles
What is the main purpose of **type as metaclass**?+
Every class is an instance of its metaclass, and type is the default one: type(Example) reports type itself unless a type subclass was involved. The three-argument form type(name, bases, namespace) performs the same creation the class statement performs, which is why a custom metaclass only has to override __new__ and delegate to super().
What should you pay attention to when using **Custom metaclasses**?+
A custom metaclass can intercept class creation, transform the namespace, register classes, or enforce constraints. The behavior affects every class using that metaclass hierarchy.
How does **__new__** fit into this lesson?+
__new__ creates and returns the new instance before __init__ initializes it. It matters most for immutable subclasses, custom allocation, and metaclass-driven construction.
Why can a registry metaclass not store `cls` before calling `super().__new__`?+
The class object does not exist until the super call returns it, so referencing cls earlier hits an unbound local name. Registration therefore has to happen after the class object is built, which is why every registry example puts the insert after the super call.