[Python] How to get the generic type at runtime

Discussão em 'Python' iniciado por Stack, Março 7, 2025.

  1. Stack

    Stack Membro Participativo

    In this snippet below, I want to get the inferred type of the generic at runtime to validate the data. How can I make the get_type so that I can get the type correctly?

    class Test[T]:
    data: Optional[T]

    def __init__(self, data: Optional[T]):
    get_type(T)

    if __name__ == "__main__":
    Test[int](data=1)
    Test[str](data=None)
    Test[None](data=None)


    I tried doing the suggestions in How to access the type arguments of typing.Generic?, but it returns either T, T~, or an empty tuple . Also, __orig_bases__ does not seem to exist any more in 3.13.

    Continue reading...

Compartilhe esta Página