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

检查类型是否为列表

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

    我有一些类型(来自 inspect.signature -> inspect.Parameter )我想看看是不是单子。我目前的解决方案很有效,但很难看,请参阅下面的最小示例:

    from typing import Dict, List, Type, TypeVar
    
    IntList = List[int]
    StrList = List[str]
    IntStrDict = Dict[int, str]
    
    TypeT = TypeVar('TypeT')
    
    # todo: Solve without using string representation of type
    def is_list_type(the_type: Type[TypeT]) -> bool:
        return str(the_type)[:11] == 'typing.List'
    
    assert not is_list_type(IntStrDict)
    assert not is_list_type(int)
    assert not is_list_type(str)
    assert is_list_type(IntList)
    assert is_list_type(StrList)
    

    检查类型是否为 List ?

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   ProfOak    6 年前

    你可以用 issubclass 要检查这样的类型:

    from typing import Dict, List, Type, TypeVar
    
    IntList = List[int]
    StrList = List[str]
    IntStrDict = Dict[int, str]
    
    TypeT = TypeVar('TypeT')
    
    # todo: Solve without using string representation of type
    def is_list_type(the_type: Type[TypeT]) -> bool:
        return issubclass(the_type, List)
    
    assert not is_list_type(IntStrDict)
    assert not is_list_type(int)
    assert not is_list_type(str)
    assert is_list_type(IntList)
    assert is_list_type(StrList)