You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Mypy检查SQLAlchemy 2.0.36注解式声明表代码时出现类型不兼容等错误的求助

Mypy检查SQLAlchemy 2.0.36注解式声明表代码时出现类型不兼容等错误的求助

我最近在用最新版的SQLAlchemy(2.0.36)配合mypy做类型检查时遇到了一堆问题,我的代码用的是注解式声明表的写法,也就是用到mapped_column那种形式。

举个例子,我的代码是这样的:

class Integration(Base):
    __tablename__ = "integration"
    id: Mapped[int] = mapped_column(primary_key=True)

    user_id: Mapped[int] = mapped_column(ForeignKey("user.id"))
    user: Mapped["User"] = relationship("User", back_populates="integrations")

    provider_accounting_id: Mapped[int] = mapped_column(ForeignKey("provider.id"))
    provider_accounting: Mapped["Provider"] = relationship(
        foreign_keys=[provider_accounting_id]
    )

    provider_webshop_id: Mapped[int] = mapped_column(ForeignKey("provider.id"))
    provider_webshop: Mapped["Provider"] = relationship(
        foreign_keys=[provider_webshop_id]
    )

    active: Mapped[bool] = Column(Boolean, nullable=False, default=False)
    sync_customer_ws_to_acc: Mapped[bool] = mapped_column(default=True)
    sync_product_ws_to_acc: Mapped[bool] = mapped_column(default=True)
    sync_order_ws_to_acc: Mapped[bool] = mapped_column(default=True)

    syncs: Mapped[t.List["Sync"]] = relationship(back_populates="integration")
    linked_objects: Mapped[t.List["LinkedObject"]] = relationship(
        back_populates="integration"
    )

运行mypy之后,我得到了这些错误:

syncly/models/integration.py:5: error: Module "sqlalchemy.orm" has no attribute "mapped_column"  [attr-defined]
syncly/models/integration.py:47: error: Incompatible types in assignment (expression has type "RelationshipProperty[User]", variable has type "Mapped[User]")  [assignment]
syncly/models/integration.py:50: error: Missing positional argument "argument" in call to "RelationshipProperty"  [call-arg]
syncly/models/integration.py:50: error: Incompatible types in assignment (expression has type "RelationshipProperty[Any]", variable has type "Mapped[Provider]")  [assignment]
syncly/models/integration.py:55: error: Missing positional argument "argument" in call to "RelationshipProperty"  [call-arg]
syncly/models/integration.py:55: error: Incompatible types in assignment (expression has type "RelationshipProperty[Any]", variable has type "Mapped[Provider]")  [assignment]

我已经尝试过安装sqlalchemy2-stubs,并且在mypy.ini文件里配置使用它,但还是没解决问题。

备注:内容来源于stack exchange,提问作者Gronnmann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 17:08:01