How to use isinstance on a generic type in Python

Viewed 2964

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.

1 Answers

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
Related