Typing Stubs for SQLAlchemy

1.4.53.38 · active · verified Thu Apr 16

types-sqlalchemy is a PEP 561 type stub package designed to provide static type checking for the SQLAlchemy library. It enables type checkers such as MyPy, Pyright, Pytype, and PyCharm to analyze code that uses SQLAlchemy, improving code quality and catching potential errors at development time. This package is part of the `typeshed` project and primarily supports SQLAlchemy 1.x, with SQLAlchemy 2.0+ integrating native type annotations. It is actively maintained as part of typeshed.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic SQLAlchemy declarative model with type hints. When `types-sqlalchemy` is installed, a static type checker (like MyPy) can analyze this code to ensure type correctness for SQLAlchemy constructs (e.g., `Column`, `String`, `Mapped`). For SQLAlchemy 2.0+, native typing is available and recommended over external stubs.

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

# types-sqlalchemy provides stubs that enable type checkers
# to understand the types of SQLAlchemy objects like Column, String, etc.

Base = declarative_base()

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

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

# Example usage (runtime, type-checked by types-sqlalchemy)
# In a real application, you would typically use an environment variable for the connection string
DATABASE_URL = "sqlite:///:memory:"
engine = create_engine(DATABASE_URL)
Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

new_user = User(name='Alice', email='alice@example.com')
session.add(new_user)
session.commit()

retrieved_user: Optional[User] = session.query(User).filter_by(name='Alice').first()
if retrieved_user:
    print(retrieved_user) # type: ignore

session.close()

view raw JSON →