![](/img/trans.png)
[英]Append an element of type (composite type) on an PostgreSQL Array using Python
[英]Get the main type out of a composite type in Python
假設我將類型定義為:
data_type1 = list[str]
data_type2 = set[int]
等等,如何通過分析兩種數據類型來獲得主要類型(如列表或集合)?
我試過了:
issubclass(data_type1, list)
issubclass(data_type2, set)
但它返回 False
任何的想法?
您可以使用__origin__
屬性。 此屬性指向非參數化泛型 class 。
>>> data_type1 = list[str]
>>> data_type1.__origin__
<class 'list'>
>>> data_type2 = set[int]
>>> data_type2.__origin__
<class 'set'>
>>> data_type2.__origin__ == set
True
或者使用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
看起來isistance
或issubclass
不支持這種類型。 這種類型稱為通用別名。
您可以在這里閱讀更多相關信息: https://docs.python.org/3/library/stdtypes.html#types-genericalias
相反,您可以使用__origin__
屬性來獲取數據類型。
(摘自上面的鏈接)
通稱。 起源
This attribute points at the non-parameterized generic class:
list[int].__origin__
<class 'list'>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.