1

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 ?
martineau
  • 119,623
  • 25
  • 170
  • 301
user1008636
  • 2,989
  • 11
  • 31
  • 45
  • As far as I know, you can only be generic in the return value when you are tying the return value to an argument. There's no type inference that lets the call site decide what type the function should return. – chepner May 13 '22 at 14:35
  • Do you want to check `T` based on what is *inferred* (`my_str: str = MyClass().my_func()`) or *defined* (`my_str = MyClass[str]().my_func()`)? – MisterMiyagi May 13 '22 at 14:44

0 Answers0