Skip to content

Python Metaclasses: Customize Class Creation

  • What a metaclass is and why type is the metaclass of almost every class.
  • The exact order of events when a class statement runs, from __prepare__ to class decorators.
  • How __init_subclass__ and __set_name__ replace most custom metaclasses.
  • The few jobs that still need a metaclass, and the errors that bite when you write one.
  • How to answer metaclass questions in a senior interview.

A metaclass is the class of a class. Calling a class creates an instance; executing a class statement calls the metaclass to create the class object. The default metaclass is type, and a custom metaclass is a subclass of type that hooks into class creation, namespace preparation or instance construction. Metaclasses have existed since the earliest new-style classes and are fully current in Python 3.14, but since Python 3.6 the __init_subclass__ and __set_name__ hooks cover most of the use cases that once required one.

Some rules apply to classes, not to objects. In the OrdersPortal app, every payment provider class must declare a code. If the check lives in __init__, a broken subclass imports cleanly and only fails when someone first instantiates it, possibly in production. A metaclass runs when the class statement itself executes, so the error appears at import time.

The samples on this page are plain scripts: save each as a .py file and run it with python3 file.py. They were run on CPython 3.14.6 and the output shown is from that run.

# Before: the rule is checked only when someone builds an instance.
class PaymentProviderV1:
def __init__(self):
if not hasattr(self, "code"):
raise TypeError(f"{type(self).__name__} must define 'code'")
class CardProviderV1(PaymentProviderV1): # forgot `code`; nothing happens yet
pass
try:
CardProviderV1() # fails much later, at runtime
except TypeError as exc:
print("at instantiation:", exc)
# After: a metaclass runs when each class statement executes.
class ProviderMeta(type):
def __new__(mcls, name, bases, namespace, **kwargs):
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
if bases and "code" not in namespace: # skip the root class itself
raise TypeError(f"{name} must define 'code'")
return cls
class PaymentProvider(metaclass=ProviderMeta):
pass
try:
class CardProvider(PaymentProvider): # fails here, at import time
pass
except TypeError as exc:
print("at class definition:", exc)
class InvoiceProvider(PaymentProvider):
code = "invoice"
print(type(InvoiceProvider).__name__, type(ProviderMeta).__name__, type(type).__name__)

Output:

at instantiation: CardProviderV1 must define 'code'
at class definition: CardProvider must define 'code'
ProviderMeta type type

The last line shows the chain: InvoiceProvider is an instance of ProviderMeta, ProviderMeta is an instance of type, and type is an instance of itself. The same rule could be written with __init_subclass__, and the realistic example below does exactly that; the metaclass version is shown first because it makes the mechanism visible.

By default, a class body runs in a fresh namespace and the class name is bound to the result of type(name, bases, namespace). You can make that call yourself, and you can see what happens when two metaclasses disagree:

# The equivalent of a class statement, done by hand.
def describe(self):
return f"{self.order_id} ({self.status})"
Order = type("Order", (), {"status": "new", "describe": describe,
"__init__": lambda self, oid: setattr(self, "order_id", oid)})
print(Order("ORD-7").describe(), type(Order))
# Metaclass conflict: two unrelated metaclasses cannot both win.
import abc
class ProviderMeta(type):
pass
class Plugin(metaclass=ProviderMeta):
pass
try:
class AuditedPlugin(Plugin, abc.ABC):
pass
except TypeError as exc:
print("TypeError:", exc)
# Fix: derive a metaclass from both.
class ProviderABCMeta(ProviderMeta, abc.ABCMeta):
pass
class AuditedPlugin(Plugin, abc.ABC, metaclass=ProviderABCMeta):
pass
print(type(AuditedPlugin).__name__)
# Metaclass methods are visible on the class, not on instances.
class Meta(type):
def table_name(cls):
return cls.__name__.lower() + "s"
class Customer(metaclass=Meta):
pass
print(Customer.table_name())
print(hasattr(Customer(), "table_name"))

Output:

ORD-7 (new) <class 'type'>
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
ProviderABCMeta
customers
False

Three rules show up here:

  • The metaclass is inherited. Any subclass of a class created by Meta is also created by Meta, without repeating metaclass=.
  • The most derived metaclass wins. Python takes the explicit metaclass (if any) and type(base) for every base, and picks the one that is a subclass of all the others. If none qualifies, the class definition fails with the metaclass conflict above. The fix is a metaclass that inherits from both, which is why mixing your own metaclass with abc.ABC, an ORM base or enum.Enum gets awkward fast.
  • Metaclass methods belong to the class. Customer.table_name() works, but instances do not see it, because instance attribute lookup searches type(obj).__mro__, not the metaclass.

The language reference lists the steps for a class definition: resolve MRO entries, determine the metaclass, prepare the namespace, execute the body, create the class object. The trace below adds the hooks that type.__new__ calls and the instance call at the end:

class TraceMeta(type):
@classmethod
def __prepare__(mcls, name, bases, **kwargs):
print(f"1. __prepare__ {name} kwargs={kwargs}")
return {}
def __new__(mcls, name, bases, namespace, **kwargs):
print(f"3. __new__ {name} body names={sorted(k for k in namespace if not k.startswith('__'))}")
return super().__new__(mcls, name, bases, namespace, **kwargs)
def __init__(cls, name, bases, namespace, **kwargs):
print(f"6. __init__ {name}")
super().__init__(name, bases, namespace, **kwargs)
def __call__(cls, *args, **kwargs):
print(f"8. __call__ {cls.__name__}{args}")
return super().__call__(*args, **kwargs)
class Field:
def __set_name__(self, owner, name):
print(f"4. __set_name__ {owner.__name__}.{name}")
class Base(metaclass=TraceMeta):
def __init_subclass__(cls, /, table=None, **kwargs):
super().__init_subclass__(**kwargs)
cls.table = table
print(f"5. __init_subclass__ {cls.__name__} table={table!r}")
def decorate(cls):
print(f"7. decorator {cls.__name__}")
return cls
@decorate
class Order(Base, table="orders"):
print("2. class body runs")
total = Field()
def __init__(self, order_id):
self.order_id = order_id
order = Order("ORD-1001")
print(type(Order).__name__, Order.table)

Output:

1. __prepare__ Base kwargs={}
3. __new__ Base body names=[]
6. __init__ Base
1. __prepare__ Order kwargs={'table': 'orders'}
2. class body runs
3. __new__ Order body names=['total']
4. __set_name__ Order.total
5. __init_subclass__ Order table='orders'
6. __init__ Order
7. decorator Order
8. __call__ Order('ORD-1001',)
TraceMeta orders

Reading the trace in order:

  1. __prepare__(name, bases, **kwargs) returns the mapping the class body will write into. It must be a classmethod. Extra keywords from the class line (table="orders") arrive here and at every later metaclass step.
  2. The class body runs like ordinary code; that is why print() inside it executes.
  3. __new__(mcls, name, bases, namespace, **kwargs) creates the class object. Inside type.__new__, Python calls __set_name__ on every attribute that defines it (step 4) and then __init_subclass__ on the parent (step 5).
  4. __init__ on the metaclass runs after the class exists, the right place for work that does not change the namespace.
  5. Class decorators run last, on the finished class.
  6. __call__ on the metaclass runs every time you instantiate the class; type.__call__ is what invokes __new__ and __init__ on the instance.

Note that __init_subclass__ never sees the metaclass keyword; it is consumed by the type machinery.

The standard library uses metaclasses where nothing lighter works: abc.ABCMeta implements virtual subclasses through __subclasscheck__, and enum.EnumType uses __prepare__ to reject duplicate member names and __iter__/__len__ so you can loop over an enum class.

OrdersPortal receives JSON messages from a queue and must turn each into the right event class. Every event class registers itself under an event_type, and duplicate or missing types must fail at import time. This needs no metaclass at all: __init_subclass__ runs for every subclass and receives the keywords from the class line.

import json
from dataclasses import dataclass
class OrderEvent:
"""Base class: every subclass registers itself under its event_type."""
registry: dict[str, type["OrderEvent"]] = {}
def __init_subclass__(cls, /, event_type: str, **kwargs):
super().__init_subclass__(**kwargs)
if event_type in OrderEvent.registry:
other = OrderEvent.registry[event_type].__qualname__
raise TypeError(f"event_type {event_type!r} already used by {other}")
cls.event_type = event_type
OrderEvent.registry[event_type] = cls
@classmethod
def from_message(cls, raw: str) -> "OrderEvent":
data = json.loads(raw)
event_cls = cls.registry[data.pop("type")]
return event_cls(**data)
@dataclass
class OrderPlaced(OrderEvent, event_type="order.placed"):
order_id: str
total: float
@dataclass
class OrderShipped(OrderEvent, event_type="order.shipped"):
order_id: str
carrier: str
print(sorted(OrderEvent.registry))
print(OrderEvent.from_message('{"type": "order.shipped", "order_id": "ORD-1001", "carrier": "DHL"}'))
try:
class OrderSentOut(OrderEvent, event_type="order.shipped"):
pass
except TypeError as exc:
print("TypeError:", exc)
try:
class OrderRefunded(OrderEvent): # forgot the class keyword
pass
except TypeError as exc:
print("TypeError:", exc)

Output:

['order.placed', 'order.shipped']
OrderShipped(order_id='ORD-1001', carrier='DHL')
TypeError: event_type 'order.shipped' already used by OrderShipped
TypeError: OrderEvent.__init_subclass__() missing 1 required positional argument: 'event_type'

Because __init_subclass__ is an ordinary (implicitly class) method on a normal base class, OrderEvent combines with @dataclass, abc.ABC and other bases without any metaclass conflict.

A metaclass earns its place when the hook must run while the class body executes. __init_subclass__ only sees the finished namespace, so it cannot detect a method that was silently redefined further down the body. __prepare__ can, by returning a mapping that refuses a second binding of the same name. enum uses the same idea.

class NoDuplicatesDict(dict):
"""Class namespace that refuses to bind the same name twice."""
def __setitem__(self, key, value):
if key in self and not key.startswith("__"):
raise TypeError(f"{key!r} is defined twice in the class body")
super().__setitem__(key, value)
class StrictMeta(type):
@classmethod
def __prepare__(mcls, name, bases, **kwargs):
return NoDuplicatesDict()
def __new__(mcls, name, bases, namespace, **kwargs):
# type.__new__ copies the namespace into a plain dict.
return super().__new__(mcls, name, bases, dict(namespace), **kwargs)
class Handlers(metaclass=StrictMeta):
pass
try:
class OrderHandlers(Handlers):
def on_order_placed(self, event):
return "reserve stock"
# ... 200 lines later, a copy-paste accident ...
def on_order_placed(self, event):
return "send email"
except TypeError as exc:
print("TypeError:", exc)

Output:

TypeError: 'on_order_placed' is defined twice in the class body

Keep such metaclasses small, put them on one root base class so users never write metaclass= themselves, and always forward **kwargs so __init_subclass__ hooks further up the hierarchy keep working.

  • Reaching for a metaclass first. Registration, validation and per-subclass configuration are __init_subclass__ jobs. A metaclass also forces every combined base to share a compatible metaclass.

  • Dropping __classcell__. If a metaclass builds a fresh namespace dict for type.__new__ and leaves out __classcell__, any method that uses zero-argument super() breaks:

    # Forgetting to pass __classcell__ on to type.__new__ breaks zero-argument super().
    class CopyingMeta(type):
    def __new__(mcls, name, bases, namespace):
    clean = {k: v for k, v in namespace.items() if k != "__classcell__"}
    return super().__new__(mcls, name, bases, clean)
    try:
    class Repo(metaclass=CopyingMeta):
    def save(self):
    return super().__repr__()
    except RuntimeError as exc:
    print("RuntimeError:", exc)
    RuntimeError: __class__ not set defining 'Repo' as <class '__main__.Repo'>. Was __classcell__ propagated to type.__new__?

    Pass the original namespace (or a copy that keeps every key) to super().__new__.

  • Swallowing class keywords. A metaclass __new__ that does not accept and forward **kwargs breaks class Order(Base, table="orders") for every __init_subclass__ in the hierarchy.

  • Expecting metaclass methods on instances. They live on the class object only; use a classmethod if instances need it too.

  • Hiding expensive work at import time. Code in a metaclass runs when the module is imported. Network calls or database lookups there slow every test run and can fail before logging is configured.

Situation Use Avoid
Subclass registry, plugin discovery __init_subclass__ (3.6+) Metaclass
Field objects that need their attribute name __set_name__ (3.6+) Metaclass scanning the namespace
Add methods to one class Class decorator or @dataclass Metaclass
Detect duplicate names or record definition order details while the body runs Metaclass __prepare__ Post-hoc checks
Custom isinstance() semantics, class-level operators Metaclass Workarounds in every caller
Application business logic Plain classes and functions Any class-creation hook

Python 3 uses the class C(metaclass=M) syntax and the __prepare__ hook (PEP 3115, Python 3.0); Python 2’s __metaclass__ class attribute is ignored in Python 3. __init_subclass__ and __set_name__ arrived in Python 3.6 (PEP 487), and the same release guaranteed that the class namespace preserves definition order. The __classcell__ requirement became a hard RuntimeError in Python 3.8. Nothing in this area changed in Python 3.14.

1. What is the metaclass of a normal class, and what is the metaclass of type? Both are type. type(Order) is type, and type(type) is type; the chain ends there because type is an instance of itself.

2. In what order do __prepare__, the class body, __set_name__, __init_subclass__, metaclass __init__ and class decorators run? __prepare__, then the class body, then metaclass __new__ (inside type.__new__: __set_name__ on attributes, then __init_subclass__ on the parent), then metaclass __init__, then class decorators from the bottom up.

3. Why do metaclass conflicts happen, and how do you fix one? Python needs one metaclass that is a subclass of the metaclasses of all bases. Two unrelated metaclasses (for example a custom one and ABCMeta) have no such common subclass. Define class Combined(MetaA, MetaB) and use it explicitly, or remove one metaclass, usually by moving its logic into __init_subclass__.

4. Senior scenario: a teammate proposes a metaclass for OrdersPortal’s domain models to auto-register them, inject audit fields and validate column types. What do you recommend? Split the request. Registration and validation belong in __init_subclass__ on a Model base, which composes with @dataclass, ABCs and ORM bases without metaclass conflicts. Audit fields are better as a mixin or an explicit dataclass field, so type checkers and IDEs can see them; attributes injected by a metaclass are invisible to static analysis. Keep a metaclass only if something must happen while the class body executes, put it on a single internal root class, forward **kwargs, preserve __classcell__, and cover it with tests that define throwaway subclasses.

  • A metaclass creates classes; type is the default, and the metaclass is inherited by subclasses.
  • A class statement runs __prepare__, the body, __new__ (with __set_name__ and __init_subclass__), __init__, then decorators.
  • Since Python 3.6, __init_subclass__ and __set_name__ handle most former metaclass jobs.
  • Use a metaclass for namespace control, isinstance() customization or behavior on the class object itself.
  • Forward **kwargs, preserve __classcell__, and avoid combining unrelated metaclasses.