Banning SQLAlchemy Dialects with Ruff

2025-11-25

This blogpost originally appeared as a YouTube video here

When working with SQLAlchemy, you might want to ensure your codebase stays portable across different database backends. SQLAlchemy supports multiple databases—SQLite, PostgreSQL, MySQL, and more — but they're all different. Sometimes, if you're building a library or larger system, you don't want developers accidentally importing PostgreSQL-specific code that breaks SQLite compatibility.

So how do you guarantee this?

Turns out, you can prevent this using Ruff.

Configuration

Here's how to set it up in your pyproject.toml:

[tool.ruff.lint.flake8-tidy-imports.banned-api]
"sqlalchemy.dialects".msg = "Only use portable SQLAlchemy types, not dialect-specific ones"

You can ban entire submodules and attach custom error messages that explain why the import is forbidden—helpful for new team members encountering the error.

Example

Say you have this code:

from sqlalchemy.dialects.sqlite import TEXT

# ... rest of your code

Running ruff check will catch it now!