[Python] Error type hinting when passing generic class itself as value, did I code something...

Discussão em 'Python' iniciado por Stack, Maio 3, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to create something like a = implemented_class_1 if condition else implemented_class_2 or even dict[key_type, implemented_classes]. But when the implemented_class comes as generic class, pyright fails to hint the typevar after selecting the specific class. Here's a simple piece of code about what I'm talking about:

    from typing import Generic, TypeVar

    T = TypeVar("T")
    class Foo(Generic[T]):
    def __init__(self, t: T):
    self.t = t

    def print(self, t: T):
    print(t, self.t)

    class Foo2(Foo[T]):
    def print(self, t: T):
    if t == self.t:
    print("equal")
    else:
    Foo.print(self, t)

    check_equal: bool
    printer = Foo2 if check_equal else Foo

    a = printer(3)
    a.print(...)


    When I'm typing the last line, VSCode is expected to hint me the type of parameter should be int, but it was hinted as Any. However, mypy is able to raise an error when I pass a non-int to a.print(), from which I believe there's nothing wrong in my code. So, Did I code anything wrong? Or may it be a bug of pyright?

    Continue reading...

Compartilhe esta Página