Metaclasses
A metaclass is the class of a class. It intercepts class creation to customise or validate class definitions — used by Django ORM, SQLAlchemy, and Pydantic.
A metaclass is the class of a class. It intercepts class creation to customise or validate class definitions — used by Django ORM, SQLAlchemy, and Pydantic.
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Database(metaclass=SingletonMeta):
def __init__(self): self.connected = True
db1 = Database()
db2 = Database()
assert db1 is db2 # same instance
Prefer class decorators or __init_subclass__ over metaclasses for most use cases — simpler and clearer.