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

Python如何为存在多种不同返回类型的函数添加类型标注

Python 多分支不同返回类型的标注方法

函数存在分支逻辑返回不同类型值时,使用联合类型语法标注即可,VSCode 安装官方 Python/Pylance 扩展后可自动识别悬浮提示,根据你使用的 Python 版本选择对应写法:

  • 通用场景:联合类型标注

    • Python 3.10 及以上版本,直接用 | 拼接所有可能的返回类型,写法最简洁:
      # 注意:不要用list作为变量名,会覆盖Python内置的list类型
      def function(x, y) -> str | list[int]:
          if x == 1:
              res_str = "test"
              return res_str
          else:
              res_list = [1, 2]
              return res_list
      
    • Python 3.5 ~ 3.9 版本,需要从标准库typing模块导入Union实现联合类型,泛型容器类型需导入对应大写别名:
      from typing import Union, List
      
      def function(x, y) -> Union[str, List[int]]:
          if x == 1:
              res_str = "test"
              return res_str
          else:
              res_list = [1, 2]
              return res_list
      
  • 高精度提示场景:重载标注

    如果需要VSCode根据入参直接推断对应分支的返回类型,而非笼统提示「可能为str或list」,可以使用@overload装饰器定义不同入参对应的精确返回类型:

    from typing import overload, Literal
    
    # 重载签名:当x传入字面量1时,返回值为str
    @overload
    def function(x: Literal[1], y) -> str: ...
    # 重载签名:当x传入其他int值时,返回值为int列表
    @overload
    def function(x: int, y) -> list[int]: ...
    # 实际实现不需要加额外标注
    def function(x, y):
        if x == 1:
            res_str = "test"
            return res_str
        else:
            res_list = [1, 2]
            return res_list
    

    配置完成后,调用函数时传入x=1,VSCode会直接判定返回值为str;传入其他整数时判定为int列表,提示精度更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 01:03:17