Reputation: 527
import typing as typ
T = typ.TypeVar("T")
class Foo(typ.Generic[T]):
"""The generic class."""
def __init__(self, var: T):
self.var = var
def var_getter(foo_obj: ??) -> ??:
"""Var getter."""
return foo_obj.var
These are the test cases that should be satisfied:
class Bar(Foo[str]):
pass
test_1 = var_getter(Bar("a")) # test_1 should be string according to type hints
class Baz(Foo[int]):
pass
test_2 = var_getter(Bar(1)) # test_2 should be int according to type hints
How would this be achieved? What would I need to use to replace the question marks in var_getter
?
Upvotes: 0
Views: 35
Reputation: 18388
from typing import Generic, TypeVar
T = TypeVar("T")
class Foo(Generic[T]):
var: T
def __init__(self, var: T):
self.var = var
class Bar(Foo[str]):
pass
class Baz(Foo[int]):
pass
def var_getter(foo_obj: Foo[T]) -> T:
return foo_obj.var
reveal_type(var_getter(Bar("a"))) # Revealed type is "builtins.str"
reveal_type(var_getter(Baz(1))) # Revealed type is "builtins.int"
Upvotes: 1