13

I'm trying to check whether an argument is an instance of the generic type specified in the class declaration. However Python does not seem to allow this.

T = TypeVar('T')
class MyTypeChecker(Generic[T]):
    def is_right_type(self, x: Any):
        return isinstance(x, T)

This gives the error 'T' is a type variable and only valid in type context.

Dax Fohl
  • 10,654
  • 6
  • 46
  • 90
  • 2
    Types hints **are not types**. There is no such thing as a "generic type* in the sense of *actual python types*. And furthermore, as is stated in the error message, `T` is a *type variable*. – juanpa.arrivillaga Apr 03 '21 at 05:36

1 Answers1

6

You could use the __orig_class__ attribute, but keep in mind that this is an implementation detail, in more detail in this answer.

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


class MyTypeChecker(Generic[T]):
    def is_right_type(self, x: Any):
        return isinstance(x, self.__orig_class__.__args__[0])  # type: ignore


a = MyTypeChecker[int]()
b = MyTypeChecker[str]()

print(a.is_right_type(1))  # True
print(b.is_right_type(1))  # False
print(a.is_right_type('str'))  # False
print(b.is_right_type('str'))  # True
alex_noname
  • 26,459
  • 5
  • 69
  • 86