i want to create a decorator to do input type checking on python functions, but i cannot get list subtypes in annotations
im trying to get the subtypes contained in a list annotation but list[str] is of type <class ‘types.GenericAlias’> so i cannot extract the str part, is there a way to do this?
>Solution :
You can get the list[str] subtypes with the __args__ attribute:
class MyClass:
my_list: list[str]
import inspect
for attribute, annotation in inspect.get_annotations(MyClass).items():
print(f'{attribute}: {annotation} with subtypes {annotation.__args__}')
# my_list: list[str] of type (<class 'str'>,)
Note that it’s a tuple, as list[str, int] is not forbidden.