pythonsqlalchemyflask-sqlalchemypython-typing

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?


Solution

  • 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]]"