SQLAlchemy 1.4 Typing Stubs

0.0.2a38 · maintenance · verified Fri Apr 10

sqlalchemy2-stubs provides interim PEP-484 typing stubs specifically for the SQLAlchemy 1.4 release series. It is an alpha-level project designed to work with a Mypy extension, replacing the older 'sqlalchemy-stubs' package. The project aims to enhance static type checking for SQLAlchemy 1.4 applications, but it is explicitly incompatible with SQLAlchemy 2.0, which features native inline typing. The current version is 0.0.2a38, and its release cadence is tied to the needs of SQLAlchemy 1.4 typing support.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a SQLAlchemy 1.4 ORM model with `sqlalchemy2-stubs` compatible type annotations using `Mapped`. The `sqlalchemy2-stubs` package itself does not have runtime code but provides type hints for tools like Mypy. Ensure Mypy is configured to use the SQLAlchemy plugin for full benefits (e.g., in `mypy.ini` or `pyproject.toml`: `[mypy] plugins = sqlalchemy.ext.mypy.plugin`).

from typing import Optional
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import Mapped, declarative_base, Session

Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    id: Mapped[int] = Column(Integer, primary_key=True)
    name: Mapped[Optional[str]] = Column(String(50))
    email: Mapped[str] = Column(String(50), nullable=False)

    def __repr__(self) -> str:
        return f"<User(id={self.id}, name='{self.name}', email='{self.email}')>"

# Example usage (not requiring sqlalchemy2-stubs at runtime, but for type checking)
if __name__ == '__main__':
    engine = create_engine('sqlite:///:memory:')
    Base.metadata.create_all(engine)

    with Session(engine) as session:
        new_user = User(name='Alice', email='alice@example.com')
        session.add(new_user)
        session.commit()
        print(f"Added user: {new_user}")

        retrieved_user = session.query(User).filter_by(name='Alice').first()
        print(f"Retrieved user: {retrieved_user}")

view raw JSON →