如何在Python类型提示中访问内部子类型?含复杂嵌套示例
访问Python类型提示中的子类型
先看你给出的示例代码:
class MyClass: prop: list[str] MyClass.__annotations__ # {'prop': list[str]}
访问简单嵌套的子类型
在Python 3.9+中,标准库泛型类型(比如list[str])可以直接通过__args__属性获取内部子类型,结合get_type_hints(比直接读__annotations__更可靠,能解析字符串形式的类型提示)使用:
from typing import get_type_hints # 获取类的类型提示 type_hints = get_type_hints(MyClass) prop_type = type_hints['prop'] # 提取list[str]中的str子类型 subtype = prop_type.__args__[0] print(subtype) # 输出: <class 'str'>
处理复杂嵌套的类型提示
对于list[set[list[list[str] | set[int]]]]这类多层嵌套的类型,我们可以写递归函数遍历类型结构,提取指定位置或所有最内层的子类型:
示例代码
from typing import get_type_hints, Union class ComplexClass: prop: list[set[list[list[str] | set[int]]]] # 提取所有最内层的基础类型 def extract_all_leaf_types(type_obj): # 处理Union类型(包括用|语法生成的联合类型) if hasattr(type_obj, '__origin__') and type_obj.__origin__ is Union: leaf_types = [] for arg in type_obj.__args__: leaf_types.extend(extract_all_leaf_types(arg)) return leaf_types # 处理泛型容器(list、set等) elif hasattr(type_obj, '__args__'): leaf_types = [] for arg in type_obj.__args__: leaf_types.extend(extract_all_leaf_types(arg)) return leaf_types # 基础类型直接返回 else: return [type_obj] # 获取指定层级的子类型(假设每层只有一个泛型参数) def get_subtype_at_level(type_obj, target_level): if target_level == 0: return type_obj if not hasattr(type_obj, '__args__'): return None return get_subtype_at_level(type_obj.__args__[0], target_level - 1) # 测试提取所有最内层类型 hints = get_type_hints(ComplexClass) complex_type = hints['prop'] all_leaf_types = extract_all_leaf_types(complex_type) print(all_leaf_types) # 输出: [<class 'str'>, <class 'int'>] # 测试获取指定层级的子类型 level_4_subtype = get_subtype_at_level(complex_type, 4) print(level_4_subtype) # 输出: str | set[int]
核心知识点
__origin__:泛型类型的原始类(比如list[str].__origin__是list),用来判断当前类型属于哪种容器。__args__:泛型类型的参数元组(比如list[str].__args__是(str,)),通过它可以拿到内部子类型。- 联合类型(Union/|)需要单独处理,遍历其所有分支类型才能覆盖所有可能的子类型。
内容的提问来源于stack exchange,提问作者Some Guy
相关产品推荐
相关产品推荐

