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:
    1. Python prepares the class namespace dictionary via MyMeta.__prepare__(name, bases, **kwargs) (returning a plain dict by default, or a custom mapping to intercept attribute definitions in order).
    2. Python executes the class body statements inside that namespace.
    3. Python calls MyMeta(name, bases, namespace, **kwargs)—invoking MyMeta.__new__ to allocate the class object and MyMeta.__init__ to initialize it.
    4. Calling Foo(...) later invokes MyMeta.__call__, which in turn calls Foo.__new__ and Foo.__init__.
  • Metaclass inheritance conflicts (TypeError: metaclass conflict):
    • If a class inherits from two base classes that use different custom metaclasses (class Child(BaseA, BaseB):), Python raises TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases unless 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.
  • When a custom metaclass is genuinely justified:
    • Customizing class object behavior itself (not instances): e.g., enum.EnumMeta (making Color.RED iterable and indexable like Color["RED"]), abc.ABCMeta (customizing isinstance()/issubclass() via __instancecheck__ and tracking @abstractmethod), or ORM declarative bases (SQLAlchemy / Django models) that transform class-level field declarations before class creation.
    • Intercepting namespace creation via __prepare__: Returning a custom dict subclass 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__.
  • Always delegate to super().__new__(mcs, name, bases, namespace):
    • Never call type.__new__(mcs, ...) directly inside a metaclass—use super().__new__(...) so cooperative multiple inheritance across combined metaclasses works properly.

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 (@dataclass, @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).