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

Python如何判断类型注解(含泛型)是否为另一类型注解的子集?

解决方案

推荐使用第三方库 typing-inspect 的 is_subtype 函数

这个库是专门用于Python类型注解运行时检查的工具,完全覆盖你需要的带泛型的类型子集判断能力,可直接替代你期望的函数f。

安装方式

pip install typing-inspect

使用示例(完全匹配你给出的期望效果)

from typing import *
from typing_inspect import is_subtype

# 你期望的f函数判断逻辑是「第二个参数是不是第一个参数的子类型」,is_subtype参数顺序相反,封装一层即可对齐
def f(parent_type, child_type):
    return is_subtype(child_type, parent_type)

print(f(Sequence, List)) # True
print(f(Sequence[str], List)) # False
print(f(Iterable[str], List[str])) # True
print(f(List[str], Iterable[str])) # False
print(f(str, str)) # True
print(f(int, str)) # False

原生issubclass的局限性说明

你遇到的TypeError: Subscripted generics cannot be used with class and instance checks是Python标准库typing模块的固有设计:带参数的泛型(比如List[str])仅用于静态类型检查,默认不支持运行时的issubclass、isinstance判断。

匹配你的最终目标:判断函数是否可组合

两个函数可组合的核心判定逻辑为:前一个函数的返回值类型 是 后一个函数的第一个输入参数类型的子类型。用上面的is_subtype可以直接实现:
假设函数A的返回类型为R1,函数B的第一个入参类型为P2,只需判断is_subtype(R1, P2)为True,即可确认两个函数支持B(A(x))形式的组合。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:15:04