-
I'm opening this discussion for workaround to the previous discussed issues using mypy with flask-sqlalchemy: In #1327, @fhd documented the workaround: from typing import TYPE_CHECKING
...
if TYPE_CHECKING:
from flask_sqlalchemy.model import Model
else:
Model = db.Model But he noted that this causes errors when using keyword arguments to the model classes. I spent a little while figuring this out, so I wanted to share my solution for that issue: When you don't define an from typing import TYPE_CHECKING
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm.decl_base import _declarative_constructor
db = SQLAlchemy()
if TYPE_CHECKING:
from flask_sqlalchemy.model import Model
else:
Model = db.Model
class Thing(Model):
__tablename___ = "things"
name: Mapped[str]
def __init__(self, *, name: str) -> None:
_declarative_constructor(self, name=name) With that, you can specify whatever mix of required and optional keywords you like. The signature for |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Your idea, as with the others, is not correct. Flask-SQLAlchemy-Lite is available to transition to. It manages engine config and sessions, but otherwise is plain SQLAlchemy, meaning all typing works. |
Beta Was this translation helpful? Give feedback.
-
I understand that it's not formally correct, and obviously creating the At any rate, I know you're a bit of sick of the topic (and reasonably so) and I didn't mean to pile on. I didn't know about Fask-SQLAlchemy-Lite, so I do appreciate the link there. Thanks for all your work! |
Beta Was this translation helpful? Give feedback.
Your idea, as with the others, is not correct.
from flask_sqlalchemy.model import Model
is not a SQLAlchemy declarative base class, it's the plain Python base class, so you're not getting any of SQLAlchemy's type checking support. Defining__init__(specific, args, names)
defeats the entire purpose of SQLAlchemy's**kwargs
support and requires doing so for every model individually.Flask-SQLAlchemy-Lite is available to transition to. It manages engine config and sessions, but otherwise is plain SQLAlchemy, meaning all typing works.