[Python] Generic[T] base class - how to get type of T from within instance?

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

  1. Stack

    Stack Membro Participativo

    Assume you have a Python class that inherits from Generic[T]. Is there any way to get a hold of the actual type passed in from within the class/instance?

    For example,

    from typing import TypeVar, Type, Generic
    T = TypeVar('T')

    class Test(Generic[T]):
    def hello(self):
    my_type = T # this is wrong!
    print( "I am {0}".format(my_type) )

    Test[int]().hello() # should print "I am int"


    On here, it is suggested the type arg would be present in in the args field of the type. And indeed,

    print( str( Test[int].__args__ ) )


    Would print (<class 'int'>,). However, I can't seem to access this from within the instance directly, e.g. substituting

    my_type = self.__class__.__args__ # this is also wrong (None)


    Doesn't seem to to the trick.

    Continue reading...

Compartilhe esta Página