Dax Fohl
Dax Fohl

Reputation: 10781

How to use isinstance on a generic type in Python

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.

Upvotes: 16

Views: 14195

Answers (1)

alex_noname
alex_noname

Reputation: 32303

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

Upvotes: 7

Related Questions