检查类型是否为lis

2024-03-28 12:42:19 发布

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

我有一些类型(来自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的检查。)


Tags: typing类型istypenotassertdictlist
1条回答
网友
1楼 · 发布于 2024-03-28 12:42:19

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

相关问题 更多 >