Python: How to specify type hints of a function that returns an attribute of a class with generic types?

Question:

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?

Asked By: TNTzx

||

Answers:

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"
Answered By: Daniil Fajnberg
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.