SQLModel Mypy plugin
Mypy plugin that improves type checking for SQLModel models.
Status
Early/experimental. Implemented scope (supported today):
- Generate correct
__init__/model_constructsignatures for SQLModel models:- treat
sqlmodel.Field(...)required/optional correctly - accept
sqlmodel.Relationship(...)kwargs fortable=Truemodels - accept common
Field(...)alias kwargs (alias/validation_alias) when statically known
- treat
- Improve SQLAlchemy expression typing for class attribute access on
table=Truemodels (e.g.User.id,User.name,Team.heroes). - Common SQLAlchemy helpers that operate on expressions / selects (e.g.
.label(...),selectinload(...),execution_options(...)) work without spurious mypy errors. - Expose SQLAlchemy table metadata on
table=Truemodels (e.g.User.__table__). - Relationship comparator typing on relationship attributes (e.g.
Team.heroes.any(...),Hero.team.has(...),Team.heroes.contains(...)). - Outer-join
Nonepropagation inselect(A, B).join(B, isouter=True)result tuples. - Broaden
Session.exec()/AsyncSession.exec()typing to accept SQLAlchemyExecutablestatements (e.g.text(...)), not justselect(...). - Optional typed
Session.execute()/AsyncSession.execute()forselect(...)(opt-in; seetyped_execute). - Accept SQLAlchemy TypeEngine instances in
Field(sa_type=...)(e.g.DateTime(timezone=True),String(50)) without# type: ignorein strict mode. - Accept
model_config = ConfigDict(...)overrides on SQLModel subclasses in strict mode. - Compatible with
pydantic.mypywhensqlmodel_mypy.pluginis listed first.
Install
uv add sqlmodel-mypy-plugin
Install (dev)
Prereqs: Python 3.10+ and uv.
make install
Run the full quality gate suite (same as CI):
make check
Enable in mypy
mypy.ini:
[mypy]
plugins = sqlmodel_mypy.plugin
If you also use pydantic.mypy, sqlmodel_mypy.plugin must be listed first:
[mypy]
plugins = sqlmodel_mypy.plugin, pydantic.mypy
This is not a preference: mypy picks the first plugin that claims a hook. If pydantic.mypy runs first, it
can treat SQLModel classes as plain Pydantic models and you’ll get incorrect typing (e.g. missing __table__,
broken SQLAlchemy expression types, and incorrect/empty constructor signatures).
Plugin configuration
All options are boolean.
Supported options:
init_typed(default:false): Generate__init__/ constructor signatures using the declared field types. Whenfalse, the plugin usesAnyfor parameter types (but still enforces required/optional fields).init_forbid_extra(default:false): Whentrue, do not add**kwargs: Anyto generated__init__/model_construct/ constructor signatures, so mypy reports unexpected keyword arguments.warn_untyped_fields(default:true): Whentrue, emit error codesqlmodel-fieldfor untyped declarations likex = Field(...)/x = Relationship(...)(usex: T = ...instead).typed_execute(default:false): Whentrue, type SQLModel’s deprecatedSession.execute()/AsyncSession.execute()for commonselect(...)statements by recoveringResult[...]generics. This is meant to reduce “type clutter” during migrations; preferSession.exec()for new code.debug_dataclass_transform(default:false): Advanced/debug-only. Whentrue, keep SQLModel’s__dataclass_transform__handling enabled in mypy (useful for debugging plugin interactions; not recommended for normal use).
mypy.ini:
[sqlmodel-mypy]
init_typed = false
init_forbid_extra = false
warn_untyped_fields = true
typed_execute = false
debug_dataclass_transform = false
pyproject.toml:
[tool.sqlmodel-mypy]
init_typed = false
init_forbid_extra = false
warn_untyped_fields = true
typed_execute = false
debug_dataclass_transform = false
Error codes
sqlmodel-field: field-related plugin errors (e.g. untypedx = Field(...)).sqlmodel-plugin-order: plugin ordering errors (e.g.pydantic.mypyenabled beforesqlmodel_mypy.plugin). Fix: listsqlmodel_mypy.pluginfirst (see Enable in mypy).
SQL expression typing
This plugin adjusts class attribute types on table=True SQLModel models to behave like SQLAlchemy
expressions, so you can write queries without col():
from sqlmodel import Field, SQLModel, select
class User(SQLModel, table=True):
id: int = Field(primary_key=True)
name: str = Field()
stmt = select(User).where(User.name.like("%x%"))
You can also use SQLAlchemy table metadata attributes without attr-defined noise:
tbl = User.__table__
getattr(Model, "field") support
If you build query filters dynamically, getattr(Model, "field") with a string literal (or a Final / string
Literal[...] name) is typed the same as direct Model.field access on table=True models:
stmt = select(User).where(getattr(User, "name").like("%x%"))
Example using a Final constant:
from typing import Final
FIELD: Final = "name"
stmt = select(User).where(getattr(User, FIELD).like("%x%"))
Non-literal names (runtime strings) are intentionally left as Any (you’ll still need a cast or a different
pattern).
Relationship comparator typing
Relationship attributes declared via Relationship(...) are typed as SQLAlchemy expressions at class level,
including common relationship comparators used in query filters:
stmt = select(Team).where(Team.heroes.any(Hero.name == "x"))
stmt = select(Hero).where(Hero.team.has(Team.name == "t"))
stmt = select(Team).where(Team.heroes.contains(hero_obj))
Out of scope
- Most SQLAlchemy-only declaration helpers: this plugin doesn’t try to “fix” the full declaration-site typing
for SQLAlchemy ORM APIs that aren’t part of SQLModel’s surface area.
- Exception: best-effort return typing for
column_property(...)(infersMapped[T]fromScalarSelect[T]/ColumnElement[T]) to support patterns likeModel._foo = column_property(...)combined withgetattr(Model, "_foo")in query builders.
- Exception: best-effort return typing for
- Pydantic
@computed_field: not touched by this plugin (it should type-check via normal property typing / Pydantic typing).
Typing strategy (defaults)
- Plugin hooks: SQLModel-specific behavior (constructor signatures,
table=Trueexpression typing, etc.). - SQLAlchemy typing: relied upon for core SQL/ORM typing wherever possible.
- Stub overlays: only for upstream gaps that can’t be addressed cleanly via hooks (prefer upstream fixes first).
Database-generated columns are optional kwargs
A field whose value the database (or SQLAlchemy) supplies on INSERT is not required in the generated
__init__ / model_construct signature. The plugin reads this off Field(...) syntactically, from
nullable=True, sa_column=Column(...) and sa_column_kwargs={...}:
| Form | Why it counts |
|---|---|
nullable=True |
column accepts NULL |
default= / insert_default= / server_default= (incl. server_default=FetchedValue()) |
an explicit default |
positional Computed(...) |
GENERATED ALWAYS AS, computed by the database |
positional Sequence(...) |
becomes Column.default, identical to default=Sequence(...) |
positional Identity(...) |
becomes Column.server_default (GENERATED ... AS IDENTITY) |
positional FetchedValue() |
becomes Column.server_default |
primary_key=True and autoincrement=True |
renders as SERIAL/IDENTITY |
Markers are matched by their resolved module, so Sequence imported from typing or
collections.abc is never mistaken for sqlalchemy.Sequence; sqlmodel re-exports of these
constructs are recognized. A name the plugin cannot trace back to SQLAlchemy is left alone.
Deliberately not covered:
- a bare
primary_key=True. SQLAlchemy's defaultautoincrement="auto"only generates a value for a single-column integer primary key, and neither the column type nor the rest of the table's primary key is knowable from oneColumn(...)call — composite or non-integer primary keys would silently become optional. Use SQLModel's usualField(default=None, primary_key=True). autoincrement=Truewithoutprimary_key=True. SQLAlchemy ignores it there (the column compiles to a plainINTEGER), so the value really is caller-supplied.
Field aliases in constructor kwargs
If you use Field(alias=...) (or validation_alias=... / schema_extra={"validation_alias": ...}), the plugin
adds the alias name as an accepted keyword argument in generated __init__ / model_construct signatures.
This avoids false-positive “unexpected keyword argument” errors when init_forbid_extra=true.
Limitations:
- Only string-literal aliases are recognized (e.g.
Field(alias=\"full_name\")). - Aliases that are not valid Python identifiers (or that collide with other parameter names) are ignored.
- Mypy can’t express “either field name or alias is required”, so aliased required fields may not be reported as missing at type-check time.
Persisted model helpers (opt-in)
Strict typing + SQLModel often means table-model IDs start as None and are populated after flush/commit/refresh
(see SQLModel: Automatic IDs, None, and Refresh).
Mypy can’t infer those runtime effects, so you can end up with repeated assert obj.id is not None.
This package ships small helpers you can import (they do not affect plugin behavior):
from sqlmodel_mypy import has_id, require_id
hero_id: int = require_id(hero) # raises ValueError if hero.id is None
if has_id(hero):
ok_id: int = hero.id
Development
- List available commands:
make help - Lint/format:
make lint/make fmt - Typecheck plugin code:
make typecheck - Run tests:
make test - Run all quality gates:
make check - Update mypy "golden" outputs:
make update-mypy
See AGENTS.md for repo conventions and workflow notes.
Security
See SECURITY.md.
Code of conduct
See CODE_OF_CONDUCT.md.
Metadata
Release files for sqlmodel-mypy-plugin 0.20.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| sqlmodel_mypy_plugin-0.20.0.tar.gz | 79.8 kB | Without provenance | Details for sqlmodel_mypy_plugin-0.20.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| sqlmodel_mypy_plugin-0.20.0-py3-none-any.whl | Python 3 | none | any | Details for sqlmodel_mypy_plugin-0.20.0-py3-none-any.whl |
Total release size: 117.7 kB
Release files / sqlmodel_mypy_plugin-0.20.0.tar.gz
| Download URL | sqlmodel_mypy_plugin-0.20.0.tar.gz |
|---|---|
| Size | 79.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d0d8e90bc2965aa5e43e7c0b8a449a931e09c7d8d836ca45c48555b7553f99e6
|
|
BLAKE2b-256 checksum How to use checksums |
b9a0e3aeab9132a17a337aeb230c8a731f21183ae268b1ee6ebcddb1c136a471
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.11.28 {"installer":{"name":"uv","version":"0.11.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / sqlmodel_mypy_plugin-0.20.0-py3-none-any.whl
| Download URL | sqlmodel_mypy_plugin-0.20.0-py3-none-any.whl |
|---|---|
| Size | 37.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
72d944c1f49ac30aed06dd65349409ac45802f0c375424c1ca5785aec9ee057b
|
|
BLAKE2b-256 checksum How to use checksums |
8a916a130124c2246a86def6810eeebabf4e9f7835ef443f3b66e336aa59e6cf
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.11.28 {"installer":{"name":"uv","version":"0.11.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for sqlmodel-mypy-plugin 0.20.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.