[英]Python: how to display nested type information?
Python 是否包含將顯示嵌套類型信息的內置類型變體,像這樣?
>>> extended_type([()])
<class 'list' containg <class 'tuple'>>
不可以。類型提示和typing
模塊以及 PEP 585 為此提供了一個表示法(即 Python 3.9 之前的list[tuple]
或List[tuple]
),但這些只能由像 MyPy 這樣的外部類型檢查器進行檢查; 沒有在運行時檢查它的能力。
PEP 585 on Making isinstance(obj, list[str]) 執行運行時類型檢查:
此功能需要迭代集合,這在其中一些是破壞性操作。 這個功能本來很有用,但是在 Python 中實現類型檢查器來處理復雜類型、嵌套類型檢查、類型變量、字符串前向引用等超出了這個 PEP 的范圍。
容器項目的類型對於容器本身的類型是不透明的。 但是,您可以為實現__iter__
東西制作自己的東西:
def extended_type(x):
types = set()
if hasattr(x, "__iter__"):
for item in x:
if item == x:
# prevent strings from infinitely recursing
continue
types.add(extended_type(item))
contains = ""
if len(types) > 0:
contains = " containing " + ", ".join(types)
return f"<class '{type(x).__name__}'{contains}>"
return f"<class '{type(x).__name__}'>"
extended_type([(1, 2, 'a'), {1: 2}])
# "<class 'list' containing <class 'tuple' containing <class 'str'>, <class 'int'>>, <class 'dict' containing <class 'int'>>>"
@Aplet123 啟發了我。
from typing import List
import json
def extended_type(obj, buffer_list: List = None):
if buffer_list is None:
buffer_list = []
buffer_list.append(f"<class '{type(obj).__name__}'>")
if hasattr(obj, '__iter__') and not isinstance(obj, str):
sub_buf = []
for item in (obj.values() if isinstance(obj, dict) else obj):
extended_type(item, sub_buf)
if sub_buf:
buffer_list.append(sub_buf)
return buffer_list
def my_func():
...
class CC:
...
data_type_info: List = extended_type([(1, 'a'),
[1, [2, '5', [2, 'a', CC()]]],
{'a': 0, 1: 2, 'b': 's', 'l': [3, 'four']},
my_func])
result: str = json.dumps(data_type_info, indent=2, sort_keys=True)
print(result)
[
"<class 'list'>",
[
"<class 'tuple'>",
[
"<class 'int'>",
"<class 'str'>"
],
"<class 'list'>",
[
"<class 'int'>",
"<class 'list'>",
[
"<class 'int'>",
"<class 'str'>",
"<class 'list'>",
[
"<class 'int'>",
"<class 'str'>",
"<class 'CC'>"
]
]
],
"<class 'dict'>",
[
"<class 'int'>",
"<class 'int'>",
"<class 'str'>",
"<class 'list'>",
[
"<class 'int'>",
"<class 'str'>"
]
],
"<class 'function'>"
]
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.