A metaclass in Python is the “class of a class”—an object (by default type) whose instances are classes themselves, controlling how a class statement’s name, base classes, and namespace dictionary are constructed into a class object at definition time; you should rarely write custom metaclasses because simpler hooks like __init_subclass__, class decorators, and descriptors solve 95%+ of class-customization needs without metaclass inheritance conflicts.
Basic Example
# 1. Every Python class is an instance of `type` (the default metaclass):
class Dog:
pass
print(type(Dog)) # Output: <class 'type'>
# 2. Custom metaclass: inherits from `type` and overrides `__new__` (or `__init__`)
class RequireDocstringMeta(type):
def __new__(mcs, name: str, bases: tuple[type, ...], namespace: dict):
if name != "BasePlugin" and not namespace.get("__doc__"):
raise TypeError(f"Class {name!r} must define a docstring")
return super().__new__(mcs, name, bases, namespace)
class BasePlugin(metaclass=RequireDocstringMeta):
"""Base plugin class."""
class ValidPlugin(BasePlugin):
"""Validates incoming payloads."""
# Defining a subclass without a docstring fails immediately at class-creation time:
# class BrokenPlugin(BasePlugin):
# pass
# Raises: TypeError: Class 'BrokenPlugin' must define a docstring
# 3. Modern Python 3.6+ alternative (NO metaclass needed for subclass validation):
class ModernBasePlugin:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if not cls.__doc__:
raise TypeError(f"Class {cls.__name__!r} must define a docstring")
Key Details & Edge Cases
- How
class Foo(Bar, metaclass=MyMeta):executes under the hood:- Python prepares the class namespace dictionary via
MyMeta.__prepare__(name, bases, **kwargs)(returning a plaindictby default, or a custom mapping to intercept attribute definitions in order). - Python executes the
classbody statements inside that namespace. - Python calls
MyMeta(name, bases, namespace, **kwargs)—invokingMyMeta.__new__to allocate the class object andMyMeta.__init__to initialize it. - Calling
Foo(...)later invokesMyMeta.__call__, which in turn callsFoo.__new__andFoo.__init__.
- Python prepares the class namespace dictionary via
- Metaclass inheritance conflicts (
TypeError: metaclass conflict):- If a class inherits from two base classes that use different custom metaclasses (
class Child(BaseA, BaseB):), Python raisesTypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its basesunless you manually create a combined diamond metaclass (class CombinedMeta(MetaA, MetaB): pass). This composability hazard is the primary reason to prefer__init_subclass__or class decorators.
- If a class inherits from two base classes that use different custom metaclasses (
- When a custom metaclass is genuinely justified:
- Customizing class object behavior itself (not instances): e.g.,
enum.EnumMeta(makingColor.REDiterable and indexable likeColor["RED"]),abc.ABCMeta(customizingisinstance()/issubclass()via__instancecheck__and tracking), or ORM declarative bases (SQLAlchemy / Django models) that transform class-level field declarations before class creation. - Intercepting namespace creation via
__prepare__: Returning a customdictsubclass from__prepare__to reject duplicate attribute definitions in the same class body or auto-assign enum values before the class is finalized. - Overriding
Meta.__call__: Intercepting instance creation across an entire class hierarchy (for instance, strict singletons or custom instantiation pipelines) without letting subclasses accidentally shadow__new__.
- Customizing class object behavior itself (not instances): e.g.,
- Always delegate to
super().__new__(mcs, name, bases, namespace):- Never call
type.__new__(mcs, ...)directly inside a metaclass—usesuper().__new__(...)so cooperative multiple inheritance across combined metaclasses works properly.
- Never call
Comparison of Class-Customization Mechanisms in Python
| Mechanism | Runs When | Can Modify Class Creation Before type.__new__? |
Risk of Multiple-Inheritance Conflicts? | Best Used When |
|---|---|---|---|---|
__init_subclass__(cls, **kwargs) (Recommended) |
Immediately after each subclass is created | No (mutates cls right after creation) |
None (cooperates cleanly via super()) |
Subclass registration (plugin registries), enforcing subclass attributes/docstrings, and parameterized inheritance (class Sub(Base, key="x"):). |
Class Decorators (, @register) |
After the decorated class is created | No (wraps or mutates cls) |
None | Explicit opt-in transformations on single classes (adding methods, validation, or metadata) without affecting subclasses automatically. |
Descriptors (__set_name__, __get__, __set__) |
At attribute definition & attribute access | No (hooks individual class attributes) | None | Reusable per-field validation, lazy properties, and ORM/typed-field attribute access rules. |
Custom Metaclass (class Meta(type):) |
Before, during (__prepare__), and at class instantiation (__call__) |
Yes (__prepare__ and __new__) |
High (TypeError: metaclass conflict) |
Building frameworks/ORMs, custom isinstance/issubclass protocols (ABCMeta), or making classes themselves iterable/subscriptable (EnumMeta). |
You must log in or register to comment.
