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

Python中递归可变长度对象的Mypy类型提示问题

解决动态分组嵌套字典的mypy类型提示问题

步骤1:定义分组结构的TypedDict

用TypedDict明确每个分组下的固定字段结构,结合TypeVar约束动态分组的键类型:

from typing import TypedDict, Dict, List, TypeVar

# 绑定分组键为字符串类型的变量
GroupKey = TypeVar('GroupKey', bound=str)

class GroupData(TypedDict):
    'from': Dict[GroupKey, List[str]]  # 键为其他分组名,值为空字符串列表
    'to': Dict[GroupKey, List[str]]
    new_products: List[str]
    removed_products: List[str]

步骤2:给函数和变量添加类型注解

在函数参数、返回值以及output变量上标注明确类型,让mypy识别动态分组结构:

def generate_group_structure(input_groups: Dict[GroupKey, List[str]]) -> Dict[GroupKey, GroupData]:
    # 给output添加明确的类型注解
    output: Dict[GroupKey, GroupData] = {}
    group_names = list(input_groups.keys())
    
    for group in group_names:
        other_groups = [g for g in group_names if g != group]
        # 初始化符合GroupData结构的分组数据
        group_data: GroupData = {
            'from': {g: [] for g in other_groups},
            'to': {g: [] for g in other_groups},
            'new_products': [],
            'removed_products': []
        }
        output[group] = group_data
    
    return output

关键说明

  • GroupKey类型变量确保输入和输出的分组键为一致的字符串类型,适配动态变化的分组名。
  • GroupData清晰定义每个分组下的必填字段及对应类型,解决动态结构的类型模糊问题。
  • 给output标注Dict[GroupKey, GroupData],直接消除mypy的"Need type annotation for 'output'"报错。

如果产品列表元素不是字符串,可将List[str]替换为对应具体类型(如List[int]或List[Any])。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:35:39