Type Stubs for SQLAlchemy-Utils

1.2.0 · active · verified Sun Apr 12

This package provides static type annotations for the `sqlalchemy-utils` library, enabling tools like MyPy to perform comprehensive type checking on code that uses `sqlalchemy-utils`'s custom data types and utilities. It currently covers various functions and types, though it is a partial stub package. The library maintains an active, albeit not rapid, release cadence, with the latest version (1.2.0) released in January 2026.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining an SQLAlchemy model using `sqlalchemy-utils.ChoiceType` with an Enum. After installing `types-sqlalchemy-utils`, a type checker like MyPy will be able to correctly infer the type of the `role` column, ensuring type safety when assigning or comparing values. The code includes a simple database interaction to illustrate runtime behavior alongside the type-checking benefits.

import sqlalchemy as sa
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy_utils import ChoiceType
from enum import Enum
from typing import cast

# Define an Enum for choices
class UserRole(Enum):
    ADMIN = 'admin'
    EDITOR = 'editor'
    VIEWER = 'viewer'

# Base for declarative models
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = sa.Column(sa.Integer, primary_key=True)
    # Use ChoiceType with the Enum; type annotation helps MyPy
    role: UserRole = sa.Column(ChoiceType(UserRole, impl=sa.String(20)))
    name: str = sa.Column(sa.String(255))

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

# Example Usage
if __name__ == "__main__":
    # In a real app, use environment variables for connection strings
    # e.g., os.environ.get('DATABASE_URL', 'sqlite:///:memory:')
    engine = sa.create_engine('sqlite:///:memory:')
    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)
    session = Session()

    # Create users with type-safe roles
    user1 = User(name='Alice', role=UserRole.ADMIN)
    user2 = User(name='Bob', role=UserRole.VIEWER)
    
    session.add_all([user1, user2])
    session.commit()

    # Query users
    admin_user = session.query(User).filter_by(role=UserRole.ADMIN).first()
    if admin_user:
        # MyPy would know admin_user.role is UserRole due to type stubs
        print(f"Found admin: {admin_user}")
        print(f"Admin role type: {type(admin_user.role)}") # Should be <enum 'UserRole'>
        # Access enum value (e.g., for comparison or display)
        if admin_user.role == UserRole.ADMIN:
            print("It's an admin!")

    session.close()

# To run type checking with MyPy:
# 1. Save the code above as `app.py`.
# 2. Ensure `sqlalchemy`, `sqlalchemy-utils`, and `types-sqlalchemy-utils` are installed.
# 3. Run: `mypy app.py`

view raw JSON →