比较打字对象的外部类型

问题描述

我正在开发一个模块,用于转换使用 Python 的 typing 库定义的类型。我想确定给定的类型是否是如下所示的列表:

def is_list(input_type):
   """Return if the given input_type is List"""
is_list(List[int]) -> True
is_list(List[str]) -> True
is_list(Dict[str,str]) -> False

此处使用 ._name 是最好的方法,还是有更好的方法提取不需要我使用私有属性的外部类型?

List[int]._name
'List'

解决方法

那是typing.get_origin

>>> typing.get_origin(typing.List[int])
<class 'list'>
>>> typing.get_origin(typing.List[int]) is list
True