【问题标题】:Check if type is a list检查类型是否为列表
【发布时间】:2019-01-05 18:26:55
【问题描述】:

我有一些类型(来自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 的正确方法是什么?

(我使用的是 Python 3.6,代码应该能够通过mypy --strict 进行检查。)

【问题讨论】:

  • 为什么不直接:if type(...) is list:
  • @Austin 因为这不适用于typing 类型别名
  • 暂时,alias.__origin__ 似乎是list 类型。不过,我正在尝试查找有关此 dunder 属性的一些文档...编辑:似乎仅适用于 3.7。
  • 或者更确切地说,在 3.6 中 List.__origin__ 返回 None,而 List[T] 将返回 typing.List,然而,这两个似乎在 Python 3.7 中都返回 list... 呃

标签: python python-3.6 typing


【解决方案1】:

您可以使用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)

【讨论】:

    猜你喜欢
    • 2021-08-03
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 2020-08-19
    • 2016-05-19
    相关资源
    最近更新 更多