I have a generic class Graph[Generic[T], object]
.
My question, is there any function which returns type passed as generic to the class Graph
>>> g = Graph[int]()
>>> magic_func(g)
<class 'int'>
I have a generic class Graph[Generic[T], object]
.
My question, is there any function which returns type passed as generic to the class Graph
>>> g = Graph[int]()
>>> magic_func(g)
<class 'int'>
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, GenericT = 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