Python深度不确定的嵌套列表的类型注解该如何定义?
深度不确定的嵌套列表类型注解方案
对于元素为整数或任意深度嵌套同结构列表的场景,需要使用递归类型注解来定义,具体实现如下:
实现方式(Python 3.10+)
通过TypeVar定义一个递归引用自身的类型,代码示例:
from typing import TypeVar # 定义递归类型:要么是int,要么是包含该类型的列表 NestedIntList = TypeVar('NestedIntList', bound='list[NestedIntList] | int') # 示例函数使用该类型注解 def traverse_nested_list(data: NestedIntList) -> None: if isinstance(data, list): for item in data: traverse_nested_list(item) else: print(f"处理整数: {data}") # 测试深度不确定的嵌套列表 sample_data = [[[1, 2]], 2, [1, [3, [3]]], 3, [2, [2]]] traverse_nested_list(sample_data)
兼容更早Python版本
如果使用Python 3.9及以下版本,需要借助typing.ForwardRef来处理类型的前向引用:
from typing import TypeVar, ForwardRef, List NestedIntList = TypeVar('NestedIntList', bound=ForwardRef('List[NestedIntList]') | int) # 需在定义后解析前向引用 from typing import get_type_hints get_type_hints(traverse_nested_list)
核心逻辑是让类型定义自身引用自身,从而覆盖任意层级的嵌套结构,完美匹配深度不确定的嵌套列表场景。
内容的提问来源于stack exchange,提问作者illuminato
相关产品推荐
相关产品推荐

