SQLAlchemy Stubs

0.4 · abandoned · verified Fri Apr 10

SQLAlchemy Stubs (version 0.4, last updated January 2021) is an experimental package providing type stubs and a Mypy plugin for the SQLAlchemy framework. Its goal was to offer more precise static types and type inference for SQLAlchemy's dynamic features. This package is now largely superseded by newer approaches to SQLAlchemy typing.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a SQLAlchemy declarative model. To benefit from `sqlalchemy-stubs`, you must install the package and configure Mypy to use its plugin by adding `plugins = sqlmypy` to your `mypy.ini` or `setup.cfg` file. Run Mypy separately on your project to enable static type checking for SQLAlchemy models.

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

# Configure Mypy (typically in mypy.ini or setup.cfg, not code)
# [mypy]
# plugins = sqlmypy

# Database setup (example using SQLite in memory)
DATABASE_URL = os.environ.get('DATABASE_URL', 'sqlite:///:memory:')
engine = create_engine(DATABASE_URL)
Base = declarative_base()
Session = sessionmaker(bind=engine)

class User(Base):
    __tablename__ = 'users'
    id: int = Column(Integer, primary_key=True)
    name: str = Column(String)

# This class will be type-checked by mypy using the stubs and plugin
# (Assuming mypy is configured and run externally)

# Example usage (not directly type-checked by sqlalchemy-stubs at runtime)
def create_user(session, user_id: int, user_name: str):
    new_user = User(id=user_id, name=user_name)
    session.add(new_user)
    session.commit()
    return new_user

if __name__ == '__main__':
    Base.metadata.create_all(engine)
    session = Session()

    # This part needs mypy run externally to show type benefits
    # For instance, mypy might catch: create_user(session, '1', 123) if types were incorrect
    user1 = create_user(session, 1, 'Alice')
    print(f"Created user: {user1.name} (ID: {user1.id})")

    session.close()

view raw JSON →