'How can I check the specific type of TypeVar? [duplicate]

If I have code like

T = TypeVar('T')

class MyClass(Generic[T]):
  @classmethod
  def my_func() -> T:
     #if T is a string:
        return "this is a string!"
     else:
        return some_other_func_that_returns_T()

There are 2 questions:

  1. how can I implement #if T is a string?
  2. even if 1) is solved, how can I return a concrete string type and not have python complain about return type mismatch on my_func ?


Solution 1:[1]

You can try the following code snnipet.

Example Code:

from typing import TypeVar, Generic

T = TypeVar('T')

class MyClass(Generic[T]):
  def my_func(self) -> T:
    if self.__orig_class__.__args__[0].__name__ == "str":
      return "this is a string!"
    else:
      return "this is not a string!"


print(MyClass[str]().my_func())
print(MyClass[int]().my_func())

Example Output:

this is a string!
this is not a string!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sabil