代码之家  ›  专栏  ›  技术社区  ›  Tobias Hermann

获取列表类型的元素类型[重复]

  •  1
  • Tobias Hermann  · 技术社区  · 6 年前

    这个问题已经有了答案:

    我有一些列表类型(来自 inspect.signature -> inspect.Parameter )我想知道它们的元素类型。我目前的解决方案很有效,但非常难看,请参阅下面的最小示例:

    from typing import List, Type, TypeVar
    
    TypeT = TypeVar('TypeT')
    
    IntList = List[int]
    StrList = List[str]
    
    # todo: Solve without string representation and eval
    def list_elem_type(list_type: Type[TypeT]) -> Type[TypeT]:
        assert str(list_type)[:11] == 'typing.List'
        return eval(str(list_type)[12:-1]) # type: ignore
    
    assert list_elem_type(IntList) is int
    assert list_elem_type(StrList) is str
    

    正确的方法是什么 List 的元素?

    (我使用的是Python3.6,代码应该可以通过检查 mypy --strict .)

    1 回复  |  直到 6 年前
        1
  •  1
  •   juanpa.arrivillaga    6 年前

    相信 你应该能够检查 __args__ 参数:

    >>> from typing import Dict, List, Type, TypeVar
    >>> List[Dict].__args__
    (typing.Dict,)
    >>> List[int].__args__
    (<class 'int'>,)
    

    但是来自 docs :

    注意 打字模块已临时列入标准库。可能会添加新功能,并且API可能会更改 即使是在核心认为必要的小释放之间 开发商。

    所以这可能不是未来的证据。