Search code examples
pythonsqlalchemymypy

mypy with SQLALchemy - error: Incompatible types in assignment


I have trouble using mypy with the latest version of sqlalchemy (2.0.36).

With code wrote using the annotated declarative form (using mapped_column).

For example, the code:

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"
    )

gives me the following errors:

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]

I have already tried installing sqlalchemy2-stubs and configuring mypy to use it in mypy.ini file without luck.


Solution

  • While searching around, I found this, which solved the issue.

    The solution is:

    1. Uninstall sqlalchemy2-stubs and/or sqlalchemy-stubs.
    2. Change the plugin in mypy.ini to plugins = sqlalchemy.ext.mypy.plugin.

    This solved the issue.