pythongenericspython-typing

How to check TypeVar's Type at runtime


I have a generic class Graph(Generic[T]).

Is there a function that returns the type arguments passed to the class Graph?

>>> g = Graph[int]()
>>> magic_func(g)
<class 'int'>

Solution

  • Here is one way to achieve this which works from Python 3.6+ (tested it in 3.6, 3.7 and 3.8):

    from typing import TypeVar, Generic
    
    T = TypeVar('T')
    
    class Graph(Generic[T], object):
        def get_generic_type(self):
            print(self.__orig_class__.__args__[0])
    
    
    if __name__=='__main__':
        g_int = Graph[int]()
        g_str = Graph[str]()
    
        g_int.get_generic_type()
        g_str.get_generic_type()
    

    Output:

    <class 'int'>
    <class 'str'>
    

    If you want to get the type inside __new__ or __init__ things get a little bit tricky, see the following post for more info: Generic[T] base class - how to get type of T from within instance?

    Edit

    The library pytypes seems to provide a method that allow to get __orig_class__ even from __init__, check the method get_orig_class available here: https://github.com/Stewori/pytypes/blob/master/pytypes/type_util.py