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

SQLAlchemy Mapped字段与mypy类型检查不兼容的问题咨询

SQLAlchemy Mapped字段与mypy类型检查不兼容的问题咨询

我遇到了一个类型检查的问题,代码如下:

from typing import Protocol
from sqlalchemy import Integer
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column


class SpamProt(Protocol):
    id: int


class Base(DeclarativeBase):
    pass


class SpamModel(Base):
   id: Mapped[int] = mapped_column(Integer())


def do_with_spam(d: SpamProt) -> None:
    raise NotImplementedError()


if __name__ == "__main__":
    spam = SpamModel(id=10)
    do_with_spam(spam)

运行mypy后返回了如下错误:

spam.py:24: error: Argument 1 to "do_with_spam" has incompatible type "SpamModel"; expected "SpamProt"  [arg-type]
spam.py:24: note: Following member(s) of "SpamModel" have conflicts:
spam.py:24: note:     id: expected "int", got "Mapped[int]"
Found 1 error in 1 file (checked 1 source file)

我知道SQLAlchemy声称没有插件的话没有完全兼容的类型支持,但我不明白为什么这么简单的例子都无法正常工作。这不是不变性导致的问题,也不是旧插件干扰的结果——我的完整依赖环境如下:

╭───────────────────┬─────────┬──────────╮
│ name              │ version │ location │
├───────────────────┼─────────┼──────────┤
│ greenlet          │ 3.1.1   │          │
│ mypy              │ 1.15.0  │          │
│ mypy-extensions   │ 1.0.0   │          │
│ SQLAlchemy        │ 2.0.39  │          │
│ typing_extensions │ 4.12.2  │          │
╰───────────────────┴─────────┴──────────╯

是不是我从根本上误解了Mapped字段的工作方式?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 19:40:30