[Python] How to annotate types for columns in sqlalchemy model

Discussão em 'Python' iniciado por Stack, Julho 10, 2025.

  1. Stack

    Stack Membro Participativo

    How do I annotate the columns in my model? The following seems to mostly work:

    class MyModel(Base):
    __tablename__: str = 'mytable'

    id: str = db.Column(db.String(32), primary_key=True)
    test: int = db.Column(db.Integer, index=True)
    is_valid: bool = db.Column(db.Boolean, default=True)


    Those type hints such as id: str remove the errors but a warning still appears for each column saying:

    Expression of type "Column[Text]" cannot be assigned to declared type "str"
    "Column[Text]" is incompatible with "str" PylancereportGeneralTypeIssues


    This is Pylance, I messed around with the mypy stuff recommended in this SO question but it didn't really help and also I imagine I shouldn't be mixing mypy with Pylance (which is pyright no?).

    I've also tried for eg. id: db.Column[Text] but that seemed to confuse the rest of my code elsewhere...

    Continue reading...

Compartilhe esta Página