Tobias Hermann
Tobias Hermann

Reputation: 10936

Check if type is a list

I have some types (coming from inspect.signature -> inspect.Parameter) and I'd like to check if they are lists or not. My current solution works but is very ugly, see minimal example below:

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)

What would be the correct way to check if a type is a List?

(I'm using Python 3.6 and the code should survive a check with mypy --strict.)

Upvotes: 0

Views: 203

Answers (1)

ProfOak
ProfOak

Reputation: 551

You can use issubclass to check types like this:

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)

Upvotes: 1

Related Questions