[英]Get the main type out of a composite type in Python
let's assume I have types defined as:假设我将类型定义为:
data_type1 = list[str]
data_type2 = set[int]
and so on, how can I get just the main type (like list or set) by analyzing the two data types?等等,如何通过分析两种数据类型来获得主要类型(如列表或集合)?
I tried:我试过了:
issubclass(data_type1, list)
issubclass(data_type2, set)
but it returns False但它返回 False
Any idea?任何的想法?
You can use __origin__
attribute.您可以使用
__origin__
属性。 This attribute points at the non-parameterized generic class . 此属性指向非参数化泛型 class 。
>>> data_type1 = list[str]
>>> data_type1.__origin__
<class 'list'>
>>> data_type2 = set[int]
>>> data_type2.__origin__
<class 'set'>
>>> data_type2.__origin__ == set
True
or usingget_origin
API from typing
module .或者使用
get_origin
API 来自typing
module 。
>>> data_type1 = list[str]
>>>
>>> from typing import get_origin
>>> get_origin(data_type1)
<class 'list'>
>>> get_origin(data_type1) == list
True
Looks like isistance
or issubclass
don't support this type.看起来
isistance
或issubclass
不支持这种类型。 This type is known as a Generic Alias.这种类型称为通用别名。
You can read more about it here: https://docs.python.org/3/library/stdtypes.html#types-genericalias您可以在这里阅读更多相关信息: https://docs.python.org/3/library/stdtypes.html#types-genericalias
Instead, you can use the __origin__
property to get the datatype.相反,您可以使用
__origin__
属性来获取数据类型。
(Extracted from the link above) (摘自上面的链接)
genericalias.通称。 origin
起源
This attribute points at the non-parameterized generic class:
list[int].__origin__
<class 'list'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.