Checking if a variable conforms to a typing object
To check if string_list
conforms to string_list_class
, you can use the typeguard type checking library.
from typeguard import check_type
try:
check_type('string_list', string_list, string_list_class)
print("string_list conforms to string_list_class")
except TypeError:
print("string_list does not conform to string_list_class")
Checking the generic type of a typing object
To check if string_list_class
is a list type, you can use the typing_inspect library:
from typing_inspect import get_origin
from typing import List
get_origin(List[str]) # -> List
You could also use the private __origin__
field, but there is no stability guarantee for it.
List[str].__origin__ # -> list
Checking the type argument of a typing object
To check the class, that string_list_class
is a list of, you can use the typing_inspect library again.
from typing_inspect import get_parameters
from typing import List
assert get_parameters(List[str])[0] == str
As before, there is also a private field you can use if you like to take risks
List[str].__args__[0] # -> str