Flask SQL Alchemy vs MyPy - error with Model type
Asked Answered
T

2

9

I came across the following problem with the combination of flask_sqlalchemy and mypy. When I define a new ORM object like:

class Foo(db.Model):
    pass

where db is a database created using SQL Alchemy applied to flask app, mypy type check produces the following error:

error: Class cannot subclass 'Model' (has type 'Any')

I would like to mention that I have sqlalchemy-stubs installed. Can someone help me with this error?

Thibaud answered 26/6, 2019 at 13:44 Comment(1)
Unfortunately, sqlalchemy-stubs contains type hints for just the sqlalchemy library, but not flask_sqlalchemy. There's an open issue asking for support for flask_sqlalchemy, but it doesn't look like anybody's started work on it yet. Perhaps you could try making your own basic stubs, taking inspiration from the existing ones? Somebody in the issue also mentioned they were able to use models from sqlalchemy directly and hook them into Flask, which let them be properly typed. Perhaps you could investigate that approach?Electrolysis
K
6

Until stubs for flask_sqlalchemy are officially supported, you can instead use sqlalchemy.orm.DeclarativeMeta to 'alias' to db.Model as pointed out in this response:

from sqlalchemy.ext.declarative import DeclarativeMeta

BaseModel: DeclarativeMeta = db.Model


class Foo(BaseModel):
    pass
Knowles answered 17/5, 2021 at 23:31 Comment(1)
DeclarativeMeta seems to have moved to sqlalchemy.orm in later versions of flask-sqlalchemy, thus the import becomes from sqlalchemy.orm import DeclarativeMetaParadisiacal
M
-4

Untill the issue is close you can set more loyal configuration MyPy for your project through mypy.ini

[mypy]
ignore_errors = True

This will ignore all non-fatal errors

Mushro answered 5/3, 2020 at 17:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.