简体   繁体   中英

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

Any idea?

You can use __origin__ attribute. This attribute points at the non-parameterized generic 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 .

>>> 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. 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

Instead, you can use the __origin__ property to get the datatype.

(Extracted from the link above)

genericalias. origin

This attribute points at the non-parameterized generic class:

list[int].__origin__
<class 'list'> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM