2

Is there any type-like command that will recurse through collections to return a pytype-style declaration if such a thing exists? I realize that collections with heterogeneous elements may be problematic.

For example, I would like to see output similar to this:

>>> fancy_type({1: {"a": 2.2}})
dict[int, dict[str, float]]
4

1 回答 1

1

据我所知,不存在这样的功能。但是,编写您在问题中描述的函数似乎相当简单:

from typing import Iterable, Mapping


def pretty_type(obj):
    obj_type = type(obj).__name__
    if isinstance(obj, Mapping):
        k, v = next(iter(obj.items()))
        return '{}[{}, {}]'.format(obj_type, pretty_type(k), pretty_type(v))
    elif isinstance(obj, Iterable) and not isinstance(obj, str):
        return '{}[{}]'.format(obj_type, pretty_type(obj[0]))
    else:
        return obj_type

测试

>>> print(pretty_type(0))
int
>>> print(pretty_type({1:{"a":2.2}}))
dict[int, dict[str, float]]
>>> print(pretty_type([1, 2, 3]))
list[int]
>>> print(pretty_type([{1:'a'}, {2:'b'}]))
list[dict[int, str]]
>>>

上面的代码可以很容易地扩展以适应任何自定义输入/输出。当然,代码显然假设元素之间是同质的。正如您在问题中指出的那样,异质元素将是有问题的,在我看来,这实际上取决于一个人对如何处理此类案件的品味。

于 2018-05-24T01:04:45.797 回答