Python:如何显示嵌套类型信息?

2024-06-16 13:05:29 发布

您现在位置:Python中文网/ 问答频道 /正文

Python是否包含一个内置的类型变量,它将显示嵌套的类型信息,比如这样

>>> extended_type([()])
<class 'list' containg <class 'tuple'>>

Tags: extended类型type内置listclasstuple类型信息
3条回答

否。类型提示和typing模块和PEP 585为此提供了一种表示法(即Python 3.9之前的list[tuple]List[tuple]),但这些仅意味着由外部类型检查器(如MyPy)进行检查;没有在运行时检查它的功能

PEP 585on使iInstance(obj,list[str])执行运行时类型检查

This functionality requires iterating over the collection which is a destructive operation in some of them. This functionality would have been useful, however implementing the type checker within Python that would deal with complex types, nested type checking, type variables, string forward references, and so on is out of scope for this 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'>"
    ]
]

相关问题 更多 >