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?

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Marcin Możejko
  • 39,542
  • 10
  • 109
  • 120
  • 3
    Unfortunately, `sqlalchemy-stubs` contains type hints for just the sqlalchemy library, but not flask_sqlalchemy. There's an [open issue](https://github.com/dropbox/sqlalchemy-stubs/issues/76) 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? – Michael0x2a Jun 26 '19 at 16:52

2 Answers2

4

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
Mks
  • 104
  • 1
  • 5
  • `DeclarativeMeta` seems to have moved to `sqlalchemy.orm` in later versions of `flask-sqlalchemy`, thus the import becomes `from sqlalchemy.orm import DeclarativeMeta` – jneuendorf Oct 12 '22 at 18:46
-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

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153