What are metaclasses and how do they work in Python?

· Category: Python Programming

Short answer

A metaclass is a class of a class. While classes define how instances behave, metaclasses define how classes behave. They allow you to customize class creation by intercepting the __new__ and __init__ calls of the class itself.

Steps

  1. Define a metaclass by subclassing type.
  2. Override __new__ or __init__ to modify class attributes.
  3. Apply the metaclass with class MyClass(metaclass=MyMeta):.
class AutoReprMeta(type):
    def __new__(mcs, name, bases, namespace):
        cls = super().__new__(mcs, name, bases, namespace)
        cls.__repr__ = lambda self: f"{name}()"
        return cls

class Point(metaclass=AutoReprMeta):
    pass

p = Point()
print(p)  # Point()

Tips

  • Metaclasses are rarely needed; prefer class decorators or __init_subclass__ for simpler use cases.
  • Libraries like Django and SQLAlchemy use metaclasses for declarative ORM models.
  • __init_subclass__ (Python 3.6+) is a cleaner way to hook into subclass creation without metaclasses.

Common issues

  • Metaclass conflicts occur when mixing classes with different metaclasses in multiple inheritance.
  • Debugging metaclass code is harder because errors occur at import time.
  • Overusing metaclasses makes code harder to understand for other developers.