Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Classes and Special Methods

Metaclasses

Concept guide to Python metaclasses: classes are objects created by type, how to write a metaclass, and why __init_subclass__ is often the simpler choice.

In Python a class is itself an object, and like every object it has a type. The type of an ordinary class is type. A metaclass is a class whose instances are classes. By choosing a different metaclass you can customize how classes are created: register them, check them, or change their attributes before they exist.

The class statement is shorthand for calling the metaclass: class Dog: ... becomes roughly Dog = type("Dog", (), namespace). Most programs never need a custom metaclass; __init_subclass__, class decorators and dataclass solve most problems more simply.

Classes are created by type

Python type() builds classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Writing a metaclass

Python A registering metaclass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second half shows the modern alternative: __init_subclass__ runs for every subclass and does the same registration with no metaclass at all.

Key rules

  • Order of events: the metaclass __prepare__ makes the namespace, the body runs, then __new__ creates the class and __init__ initializes it. __call__ on the metaclass controls what Cls() does (used for singletons).
  • Inheritance: a class uses the most derived metaclass among its bases; incompatible metaclasses raise TypeError: metaclass conflict.
  • Metaclass methods are visible on the class but not on its instances.
  • ABCMeta (abstract base classes) and EnumMeta are the metaclasses you already use.
  • Prefer simpler tools: __init_subclass__ for hooks on subclasses, class decorators for modifying one class, __set_name__ for descriptors.
  • Use a metaclass only when you must change class creation itself, such as altering the namespace or controlling instance creation for every subclass.
  • Keywords: class A(Base, flag=True) passes flag to the metaclass and to __init_subclass__.
  • Debugging cost: metaclasses make code harder to read; document them well.