6

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'>
martineau
  • 119,623
  • 25
  • 170
  • 301
jastor_007
  • 371
  • 4
  • 14

1 Answers1

5

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

Julian Mehnle
  • 156
  • 11
Isma
  • 14,604
  • 5
  • 37
  • 51