What are Python Metaclasses?
In Python, everything is an object, including classes themselves! A metaclass is the blueprint used to create classes. If a class defines how an object is created, a metaclass defines how a class is created.
python
Creating Your Own Metaclass: __new__
By default, Python uses the
type metaclass to build classes. To create a custom metaclass, you inherit from type and override the __new__ method.python
The Modern Solution: __init_subclass__ (Python 3.6+)
Metaclasses are often too complex and overkill for simple tasks (like registering plugins or validation). Most of the time, you should use
__init_subclass__ instead. It's a method you define in a parent class that is automatically called whenever a new subclass is created.python
Summary
| Term | Description |
|---|---|
| type | The default metaclass for all classes in Python |
| metaclass= | Keyword used to define a custom metaclass |
| new | Method where the class is physically created |
| init_subclass | The safer, modern way to hook into class creation |
| Best For | Plugin systems, DB Models (Django/SQLAlchemy), Validation |
| Caution | High complexity; use inheritance or decorators first! |