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

如何为与*args长度一致但元素类型不同的元组添加类型注解?

精准注解输入输出长度一致的元组函数

当函数通过*args接收任意数量的整数参数,返回的元组长度与输入参数数量完全匹配,且每个元素是输入值加1后的字符串时,如何做准确的类型注解?

以这个函数为例:

def add_one_and_to_str(*args):
    return tuple(str(i+1) for i in args)

现有方案的局限

用Sequence[str]的问题

from typing import Sequence

def add_one_and_to_str(*args: int) -> Sequence[str]:
    return tuple(str(i+1) for i in args)

这种注解无法传达两个关键信息:返回的是元组而非任意序列,以及返回元组的长度和输入参数数量完全一致。

用TypeVarTuple的局限(Python 3.11+)

from typing import TypeVarTuple, Tuple

Ts = TypeVarTuple('Ts')

def make_tuple(*args: *Ts) -> Tuple[*Ts]:
    return args

TypeVarTuple能保留元组长度信息,但仅适用于输入输出类型完全相同的场景,且目前不支持类型边界,无法限制输入必须为整数。

正确的注解方法

在Python 3.11及以上版本,结合TypeVar(带类型边界)和TypeVarTuple可以实现精准注解:

from typing import TypeVar, TypeVarTuple, Tuple

# 限制输入参数必须是int或其子类
T = TypeVar('T', bound=int)
# 捕获输入参数的长度信息
Ts = TypeVarTuple('Ts')

def add_one_and_to_str(*args: *Tuple[T, ...]) -> Tuple[*Tuple[str, ...]]:
    return tuple(str(i+1) for i in args)

如果不需要支持子类,也可以直接简化为:

from typing import TypeVarTuple, Tuple

Ts = TypeVarTuple('Ts')

def add_one_and_to_str(*args: *Tuple[int, ...]) -> Tuple[*Tuple[str, ...]]:
    return tuple(str(i+1) for i in args)

这种注解能让类型检查工具(如mypy、pyright)识别:

  • 所有输入参数必须是整数类型
  • 返回值是元组,长度与输入参数数量完全一致
  • 返回元组的每个元素都是字符串

Python 3.12+还可以用Unpack语法让代码更清晰:

from typing import TypeVarTuple, Tuple, Unpack

Ts = TypeVarTuple('Ts')

def add_one_and_to_str(*args: Unpack[Tuple[int, ...]]) -> Tuple[Unpack[Tuple[str, ...]]]:
    return tuple(str(i+1) for i in args)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:05:55