class statement, and special dunder methods let you hook into nearly every built-in Python operation. These mechanics underpin modern frameworks like FastAPI, Pydantic, and SQLAlchemy. Understanding them turns “magic happens here” into clear, predictable behaviour you can reason about and extend.
Abstract Base Classes (ABC)
An Abstract Base Class defines a set of methods that subclasses must implement. This enforces an API contract at class-instantiation time.ABC and @abstractmethod come from Python’s built-in abc module. A class with at least one unimplemented abstract method cannot be instantiated.Classes are Objects — Metaclasses
In Python, every class is itself an object, and that object was created by a metaclass. By default, all classes are instances of the built-in metaclasstype:
Dynamic Class Creation with type()
Because type is a callable, you can create classes programmatically using its three-argument form:
class statement.
Special Attributes: __dict__ and __annotations__
__dict__
Every class and instance has a __dict__ — a namespace dictionary containing its attributes and methods:
__annotations__
Type hints defined on a class are stored in __annotations__. Libraries like Pydantic and dataclasses read this dictionary at runtime to drive validation and code generation:
Dunder Methods (Magic Methods)
Dunder methods let you hook into Python’s built-in operations and protocols.Class Creation Stages
When Python executes aclass statement, it follows these steps:
1
Compile the class body
Python compiles the class body into a namespace dictionary.
2
Identify the metaclass
Python determines which metaclass to use (default:
type).3
Metaclass __new__ runs
The metaclass allocates and constructs the class object.
4
Metaclass __init__ runs
The metaclass configures and registers the class object.
5
Class is bound to its name
The class object is assigned to the name in the current scope.
Real-World Framework Implementations
Advanced OOP mechanics are the backbone of modern Python frameworks.SQLAlchemy — Declarative ORM
SQLAlchemy uses metaclasses to automatically map Python class attributes to database columns. When your class inherits fromDeclarativeBase:
- The metaclass reads class attributes like
id = Column(Integer). - It uses the class name to register a database table.
- Attribute access like
user.name = "Rahul"becomes a tracked database operation.
FastAPI / Pydantic — Data Validation
Pydantic uses metaclasses and__annotations__ for automatic serialisation and validation:
- When a class inherits from
BaseModel, Pydantic’s metaclass reads__annotations__at class-definition time. - It builds validators for each type hint (e.g.,
age: intgenerates an integer coercion function). - FastAPI passes incoming HTTP request data through these validators before your endpoint function ever runs, providing clear error messages for invalid input.
Practical Example: Pydantic reads __annotations__
Practical Example: Pydantic reads __annotations__