Get TypeVars of custom Generic Class from instance

289 views Asked by At

I have something like this:

from typing import TypeVar, Generic, Tuple

T = TypeVar('T')
S = TypeVar('S')
U = TypeVar('U')

class Foo(Generic[T, S]):
    def get_type_vars(self) -> Tuple[TypeVar]:
        return  #TODO how do I return T and S here?

assert Foo().get_type_vars() == (T, S)

Is there any way to get this behavior? I need a way to find out, that S and T are the TypeVars of the generic Class Foo. Any ideas?

I should mention that I write some class decorators and the method get_type_vars() will be added to the class by a decorator. So all I have is the instance self in the method:

def get_type_vars(self) -> Tuple[TypeVar]:
        return  #TODO how do I return T and S here in case that self is an instance of Foo?
1

There are 1 answers

1
Corentin Pane On BEST ANSWER

You can use get_args combined with __orig_bases__ to inspect generic types of the base class:

class Foo(Generic[T, S]):
    def get_type_vars(self) -> Tuple[TypeVar]:
        return get_args(type(self).__orig_bases__[0])

This would get a bit more complicated for more complex inheritance chains though.