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
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
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 whatCls()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) andEnumMetaare 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)passesflagto the metaclass and to__init_subclass__. - Debugging cost: metaclasses make code harder to read; document them well.