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

使用Django-Ninja+MyPy时[return-value]类型匹配错误排查

Django-Ninja + MyPy 返回值类型匹配问题

在使用Django-Ninja结合MyPy时遇到了[return-value]错误:MyPy判定返回的tuple[int, dict[str, str]]不符合tuple[int, None] | tuple[int, DetailType]类型,但实际上该返回值完全符合联合类型中的第二种情况。在代码的其他部分,MyPy能正确识别该字典包含detail键,但使用Union[...]后,它似乎无法递归识别嵌套的类型。

错误信息

apps/users/views.py:106: error: Incompatible return value type (got "tuple[int, Message]", expected "tuple[int, None] | tuple[int, DetailType]")  [return-value]

类型定义

DetailType = TypedDict("DetailType", {"detail": str})
MessageType = tuple[int, DetailType]
NoContentType = tuple[int, None]

报错代码片段

@post("me/password/change/", response={204: None, 401: Message}, url_name="users_me_password_change")
def change_password(request: HttpRequest, data: ChangePasswordRequest) -> Union[NoContentType, MessageType]: <<< 此处为返回类型标注
    user = request.user
    if not user.check_password(data.password):
        return 401, {"detail": "Password is incorrect."} <<< MyPy错误触发行
    user.set_password(data.new_password)
    user.save()
    return 204, None

内容的提问来源于stack exchange,提问作者Jože Kuhar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 10:03:20