比较打字对象的外部类型

时间:2021-02-13 18:12:33

标签: python python-3.8

我正在开发一个模块,用于转换使用 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'

1 个答案:

答案 0 :(得分:4)

那是typing.get_origin

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