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

使用函数返回类型时Mypy报错,如何让Mypy识别该写法?

解决Typer场景下Mypy对自定义注解函数的类型报错问题

针对你遇到的问题,这里提供几种可行的解决方案:

方案1:用Annotated包装类型与Typer配置

将string_prompt设计为返回Annotated[str, typer.Argument]的函数,同时通过类型标注让Mypy识别其返回值为合法类型:

import typer
from typing import Annotated, TypeAlias

def string_prompt(prompt_text: str) -> TypeAlias:
    return Annotated[str, typer.Argument(prompt=prompt_text)]

# 使用示例
def main(username: string_prompt("请输入用户名:")):
    typer.echo(f"欢迎,{username}!")

if __name__ == "__main__":
    typer.run(main)

Annotated既保留了str的类型信息供Mypy检查,又能让Typer读取内部的Argument配置,完美兼顾类型检查与业务需求。

方案2:强制类型转换让Mypy识别返回值

如果不想用Annotated,可以通过typing.cast告诉Mypy,string_prompt返回的是str的类型对象:

import typer
from typing import cast, Type

def string_prompt(prompt_text: str) -> Type[str]:
    return cast(Type[str], typer.Argument(prompt=prompt_text))

# 使用示例
def main(email: string_prompt("请输入邮箱:")):
    typer.echo(f"邮箱已记录:{email}")

这种方式用类型转换跳过Mypy对返回值的类型校验,同时保留Typer的注解解析逻辑。

方案3:启用Typer官方Mypy插件

Typer提供了专门的Mypy插件,能直接识别typer.Argument/Option作为合法注解,无需修改代码:

  1. 安装插件:
pip install mypy-typer-plugin
  1. 在项目的mypy.ini或pyproject.toml中启用插件:
[mypy]
plugins = mypy_typer_plugin.main

之后Mypy就能正确识别你原来的string_prompt函数调用,不再报错。

内容的提问来源于stack exchange,提问作者Jan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 17:33:29