Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 498
Patrick B. Avatar asked Oct 13 '25 11:10

Patrick B.


2 Answers

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.

like image 197
Kiran Jonnalagadda Avatar answered Oct 15 '25 03:10

Kiran Jonnalagadda


Install sqlalchemy with sqlalchemy2-stubs

poetry add "sqlalchemy[mypy]"

And then update mypy.ini with

[mypy]
plugins = sqlalchemy.ext.mypy.plugin
like image 26
Sagan Avatar answered Oct 15 '25 04:10

Sagan