SQLAlchemy Stubs
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
- breaking The `sqlalchemy-stubs` package is superseded by SQLAlchemy 2.0's native, inline type annotations. Installing `sqlalchemy-stubs` or `sqlalchemy2-stubs` (for SQLAlchemy 1.4) can cause type conflicts and incorrect behavior with SQLAlchemy 2.0+.
- deprecated This project (version 0.4) is no longer actively maintained and has not seen updates since January 2021. Its functionality has been largely replaced by the SQLAlchemy project's own typing efforts.
- gotcha The Mypy plugin provided by `sqlalchemy-stubs` must be explicitly enabled in your Mypy configuration file (e.g., `mypy.ini` or `setup.cfg`) via `plugins = sqlmypy`. Without this, the stubs will not provide enhanced type inference.
- gotcha The `sqlalchemy-stubs` package is marked as 'Alpha' and may not fully cover all SQLAlchemy features or edge cases, potentially leading to incomplete type inference (`Any`) or false positive errors.
Install
-
pip install sqlalchemy-stubs
Imports
- Plugin Configuration
[mypy] plugins = sqlmypy
Quickstart
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()