ldrg
ldrg

Reputation: 4501

How do I get PEP 484 type hints for flask_sqlalchemy classes?

How do I get PEP 484 type hints with the flask_sqlalchemy package? I see that there are type hints for SQLAlchemy provided by a third party, but is it possible to hook these up for models and queries defined with flask_sqlalchemy?

Upvotes: 10

Views: 1747

Answers (2)

danilo-ac
danilo-ac

Reputation: 11

if you would like get hints from query property from model, ie. MyModel.query.all() , try it:

from flask_sqlalchemy import BaseQuery

class MyModel(SomeCustomBaseModel):
  __tablename__ = "some_table"

# some columns definitions 

query: BaseQuery # <- this typed attr will show sqlalchemy methods (all, first, one, ...) hints at least in VSCode

Upvotes: 1

Kracekumar
Kracekumar

Reputation: 20419

There is a Flask SQLAlchemy Stubs which you can add to your mypy config as follow as

[mypy]
plugins = flasksqlamypy

Flask SQLAlchemy specific code typing code can be placed inside TYPE_CHECKING constant.

Here is an example:

from typing import TYPE_CHECKING
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

if TYPE_CHECKING:
    from flask_sqlalchemy.model import Model

    BaseModel = db.make_declarative_base(Model)
else:
    BaseModel = db.Model

class User(BaseModel):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)

user = User(id=42, name=42)  # Error: Incompatible type for "name" of "User"
                             # (got "int", expected "Optional[str]")
user.id  # Inferred type is "int"
User.name  # Inferred type is "Column[Optional[str]]"

Upvotes: 5

Related Questions