Patrick B.
Patrick B.

Reputation: 12343

Why does mypy does not work with sqlalchemy?

I have the following code (snippet):

from sqlalchemy.orm import declarative_base

Base = declarative_base()

with pip I installed

$ pip install -U sqlalchemy[mypy] sqlalchemy-stubs mypy
$ pip list | egrep -i '(sqlal|mypy)'
mypy                          0.982
mypy-extensions               0.4.3
SQLAlchemy                    1.4.42
sqlalchemy-stubs              0.4
SQLAlchemy-Utils              0.38.3
sqlalchemy2-stubs             0.0.2a29

Still, when running mypy file.py, I'm getting:

$ python3 -mmypy test.py 
test.py:1: error: Module "sqlalchemy.orm" has no attribute "declarative_base"
Found 1 error in 1 file (checked 1 source file)

I'm using Python 3.10.5 from within a virtualenv.

What can I do to debug more?

Upvotes: 4

Views: 7839

Answers (3)

Kiran Jonnalagadda
Kiran Jonnalagadda

Reputation: 2826

SQLAlchemy 2.0 was completely overhauled for native compatibility with static type checking. You will have to refactor existing code following the migration guide. There is a deprecated Mypy plugin that can be used in the interim, but I found it unstable (several months ago) so I gave up on it and refactored my code.

Upvotes: 4

Sagan
Sagan

Reputation: 2343

Install sqlalchemy with sqlalchemy2-stubs

poetry add "sqlalchemy[mypy]"

And then update mypy.ini with

plugins = sqlalchemy.ext.mypy.plugin

Upvotes: 5

bitflip
bitflip

Reputation: 3674

I think its a problem of sqlalchemy.

sqlalchemy.ext.declarative package is now integrated into the sqlalchemy.orm namespace

https://docs.sqlalchemy.org/en/14/changelog/migration_14.html#change-5508

Seems like its not working correctly with mypy, but I didnt dig deeper.

It is working fine, when I import declarative_base "the old way" like this:

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

Upvotes: 2

Related Questions