Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract list subtypes from python list

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading