Search code examples
pythontype-hinting

Access subtype of type hint


class MyClass:
    prop: list[str]

MyClass.__annotations__
# {'prop': list[str]}

How do I access "str"?

As a more generic question, given an obnoxiously complex and long type hint, like prop: list[set[list[list[str] | set[int]]]], how do I access the internal values programmatically?


Solution

  • Here is a function that will recursively pretty print the type and all the types inside it, using typing.get_args as suggested by @user2357112 :

    from typing import List, Set, Union
    import typing
    
    complex_type = Union[List[str], Set[int]]
    
    def log_type_layers(typing_type, indent=4, depth=0):
        current_type = typing_type
        print(" "*indent*depth + str(current_type))
        for subtype in typing.get_args(current_type):
            log_type_layers(subtype, indent=indent, depth=depth+1)
            
    log_type_layers(complex_type)
    

    Output:

    typing.Union[typing.List[str], typing.Set[int]]
        typing.List[str]
            <class 'str'>
        typing.Set[int]
            <class 'int'>