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

Python中函数返回多类型时,如何指定接收变量的类型?

Python解包多返回值时的类型标注方法

你尝试的写法存在语法问题,同时可能忽略了Python版本或类型检查工具的支持情况,以下是几种正确的实现方式:

方式一:先声明变量并标注类型,再解包赋值

这是兼容性最好的写法,适用于所有支持类型提示的Python版本:

from typing import Tuple, List

def test() -> Tuple[str, int, List[int]]:
    return 'abc', 100, [0, 1, 2]

# 先标注每个变量的类型
a: str
b: int
c: List[int]
# 再执行解包赋值
a, b, c = test()

方式二:同一行直接给每个变量标注类型

Python 3.6+支持这种紧凑写法,只要语法正确(每个变量后紧跟: 类型),主流类型检查工具(如mypy、pyright)都能识别:

from typing import Tuple, List

def test() -> Tuple[str, int, List[int]]:
    return 'abc', 100, [0, 1, 2]

# 直接在解包时标注每个变量类型
a: str, b: int, c: List[int] = test()

如果你的代码报错,可能是Python版本过低,或者类型检查工具未正确配置。另外从Python 3.9开始,无需导入List,直接用list[int]即可:

def test() -> tuple[str, int, list[int]]:
    return 'abc', 100, [0, 1, 2]

a: str, b: int, c: list[int] = test()

注意点

你之前写的ret: Tuple(str, int, List[int])存在语法错误,Tuple的类型参数需要用方括号包裹,正确写法是ret: Tuple[str, int, List[int]],但这种方式确实需要后续手动解包,不如直接给单个变量标注高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:15:33