Type Stubs for SQLAlchemy-Utils
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
- gotcha This is a partial stub package, meaning it does not cover all functions and objects available in the `sqlalchemy-utils` library. Type checking might not be fully comprehensive for all features.
- breaking The official SQLAlchemy MyPy plugin for versions 1.x is deprecated in SQLAlchemy 2.0 and later, where an all-new typing system is featured. Ensure compatibility with your SQLAlchemy version. `types-sqlalchemy-utils` relies on `sqlalchemy2-stubs` for core SQLAlchemy typing.
- gotcha This package provides type annotations and is not meant for direct import in your application code. You should import actual components from the `sqlalchemy-utils` library. `types-sqlalchemy-utils` works in the background with your type checker to provide static analysis.
- gotcha The `sqlalchemy-utils` library itself must be installed separately at runtime for your application to function. `types-sqlalchemy-utils` only provides static type information.
Install
-
pip install types-sqlalchemy-utils
Imports
- ChoiceType
from sqlalchemy_utils import ChoiceType
- CountryType
from sqlalchemy_utils import CountryType
Quickstart
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`