Python Metaclasses: Customize Class Creation
What you’ll learn
Section titled “What you’ll learn”- What a metaclass is and why
typeis the metaclass of almost every class. - The exact order of events when a
classstatement 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.
Summary
Section titled “Summary”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.
The problem it solves
Section titled “The problem it solves”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 runtimeexcept 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 passexcept 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 typeThe 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.
How it works
Section titled “How it works”A class statement is a call
Section titled “A class statement is a call”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): passexcept 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 basesProviderABCMetacustomersFalseThree rules show up here:
- The metaclass is inherited. Any subclass of a class created by
Metais also created byMeta, without repeatingmetaclass=. - 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 withabc.ABC, an ORM base orenum.Enumgets awkward fast. - Metaclass methods belong to the class.
Customer.table_name()works, but instances do not see it, because instance attribute lookup searchestype(obj).__mro__, not the metaclass.
The order of events
Section titled “The order of events”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
@decorateclass 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__ Base1. __prepare__ Order kwargs={'table': 'orders'}2. class body runs3. __new__ Order body names=['total']4. __set_name__ Order.total5. __init_subclass__ Order table='orders'6. __init__ Order7. decorator Order8. __call__ Order('ORD-1001',)TraceMeta ordersReading the trace in order:
__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.- The class body runs like ordinary code; that is why
print()inside it executes. __new__(mcls, name, bases, namespace, **kwargs)creates the class object. Insidetype.__new__, Python calls__set_name__on every attribute that defines it (step 4) and then__init_subclass__on the parent (step 5).__init__on the metaclass runs after the class exists, the right place for work that does not change the namespace.- Class decorators run last, on the finished class.
__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.
Where metaclasses are still used
Section titled “Where metaclasses are still used”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.
Realistic example
Section titled “Realistic example”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 jsonfrom 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)
@dataclassclass OrderPlaced(OrderEvent, event_type="order.placed"): order_id: str total: float
@dataclassclass 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"): passexcept TypeError as exc: print("TypeError:", exc)
try: class OrderRefunded(OrderEvent): # forgot the class keyword passexcept 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 OrderShippedTypeError: 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.
Production patterns
Section titled “Production patterns”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 bodyKeep 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.
Common mistakes
Section titled “Common mistakes”-
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 fortype.__new__and leaves out__classcell__, any method that uses zero-argumentsuper()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**kwargsbreaksclass 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.
When to use it and when not to
Section titled “When to use it and when not to”| 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 |
Compatibility
Section titled “Compatibility”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.
Interview questions
Section titled “Interview questions”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.
Key takeaways
Section titled “Key takeaways”- A metaclass creates classes;
typeis 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.
Related pages
Section titled “Related pages”- Method resolution order: how the bases you list become
__mro__. - Descriptors: the protocol behind
__set_name__, properties and methods. - Magic methods: the special methods a metaclass can define for classes.
- @staticmethod vs @classmethod: why
__init_subclass__is implicitly a classmethod. - dataclasses: generated methods via a class decorator instead of a metaclass.
- Protocols: structural typing as an alternative to ABC registration.
- Object-oriented programming: classes, inheritance and composition basics.
Official references
Section titled “Official references”- Data model: Customizing class creation and Metaclasses (Python 3.14 docs)
- Data model: Creating the class object (Python 3.14 docs)
- Built-in function type() (Python 3.14 docs)
- abc: Abstract Base Classes (Python 3.14 docs)
- What’s New in Python 3.6: simpler customization of class creation
- PEP 3115: Metaclasses in Python 3000
- PEP 487: Simpler customisation of class creation