Phase 17 of 25 · Topic 17.2

SQLAlchemy 2.0 Modern Declarative Mappings

1Concept

SQLAlchemy 2.0 introduced modern declarative mappings using `Mapped[]` type hints and `mapped_column()`. It eliminates legacy column boilerplate, providing full type safety and seamless Mypy integration.

2Architecture Diagram

class User(Base):
  id: Mapped[int] = mapped_column(primary_key=True)
  email: Mapped[str] = mapped_column(String(255), unique=True)

3Code Example

Python 3.12
# SQLAlchemy 2.0 Model Pattern
schema_demo = '''
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import String

class Base(DeclarativeBase):
    pass

class Account(Base):
    __tablename__ = "accounts"

    id: Mapped[int] = mapped_column(primary_key=True)
    username: Mapped[str] = mapped_column(String(50), unique=True)
    balance: Mapped[float] = mapped_column(default=0.0)
'''
print("=== SQLAlchemy 2.0 Declarative Mapping ===")
print(schema_demo.strip())

4Expected Output

=== SQLAlchemy 2.0 Declarative Mapping ===
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import String

class Base(DeclarativeBase):
    pass

class Account(Base):
    __tablename__ = "accounts"

    id: Mapped[int] = mapped_column(primary_key=True)
    username: Mapped[str] = mapped_column(String(50), unique=True)
    balance: Mapped[float] = mapped_column(default=0.0)

5Key Takeaways

  • SQLAlchemy 2.0 uses `DeclarativeBase` instead of legacy `declarative_base()` factory.
  • `Mapped[T]` provides static type checking without third-party plugins.
  • `mapped_column()` infers column types directly from the Python type hint (e.g. `int` -> `Integer`).