How do I assign a variable value as a type hint? I have attached a sample code for what I want to achieve:
class Class1:
var1 = 1
class Class2:
var2 = 2
class BaseClass:
def __init__(self, var):
self.var = var
class ChildClass1(BaseClass):
def __init__(self):
super().__init__(var=Class1)
def fun(self):
self.var. # How to get type hint here for Class1 like it should show var1
class ChildClass2(BaseClass):
def __init__(self):
super().__init__(var=Class2)
def fun(self):
self.var. # How to get type hint here for Class2 like it should show var2
Edit 1: By "type hint" I mean that after typing self.var
the intellisense of the IDE should give my recommendations like those we get when we type str().
and then we get e.g. strip()
.
Edit 2: @DaniilFajnberg Gave a nice solution to the problem ie Generics, but still keeping the question as active because I am looking for solutions other than Generics (I already mentioned that in a comment).
I know you specifically mentioned in the comments that you don't want generics, but since they are the textbook solution to this problem, maybe somebody else coming across this question will find this useful:
from typing import Generic, TypeVar
T = TypeVar("T")
class Class1:
var1 = 1
class Class2:
var2 = 2
class BaseClass(Generic[T]):
var: type[T]
def __init__(self, var: type[T]) -> None:
self.var = var
class ChildClass1(BaseClass[Class1]):
def __init__(self) -> None:
super().__init__(var=Class1)
class ChildClass2(BaseClass[Class2]):
def __init__(self) -> None:
super().__init__(var=Class2)
if __name__ == '__main__':
child1 = ChildClass1()
child2 = ChildClass2()
reveal_type(child1.var) # this line is for mypy
reveal_type(child2.var) # this line is for mypy
This results in mypy
giving the following output:
[...].py:35: note: Revealed type is "Type[[...].Class1]"
[...].py:36: note: Revealed type is "Type[[...].Class2]"
Any worthwhile IDE will give you the desired auto-suggestions with this setup.
Remember that runtime type annotations are a contradiction in terms.