I am trying to use a TypeVar to indicate an init parameter as a certain type. But I am doing it wrong, or it might not even be possible.
from typing import TypeVar T=TypeVar("T") class TestClass: def __init__(self,value:T): self._value=value a = TestClass(value=10) b = TestClass(value="abc") reveal_type(a._value) reveal_type(b._value) I was hoping the reveal type of a._value would have been int and b._value to have been string. But they are both revealed as 'T`-1'
Any help or insight appreciated!
[EDIT]
A little more expanded example. The BaseClass will be overridden and the actual type hint is provided by the overriding class.
from typing import TypeVar T=TypeVar("T") class BaseClass: def __init__(self,value): self._value = value class Class1(BaseClass): def __init__(self,value:str): super().__init__(value) class Class2(BaseClass): def __init__(self,value:int): super().__init__(value) a = Class1("A value") b = Class2(10) reveal_type(a._value) reveal_type(b._value)
TestClassto be generic or something?TestClassas generic, i.e.class TestClass(Generic[T]):. Otherwise, the conrcete type ofTis only scoped to the method and lost afterwards.