[Python] How to avoid repeating type hints when overriding a parent method?

Discussão em 'Python' iniciado por Stack, Agosto 14, 2025.

  1. Stack

    Stack Membro Participativo

    I have this code:

    class A:
    def f(self, a: int) -> int:
    raise NotImplementedError

    class B(A):
    def f(self, a):
    return a


    However mypy --strict tells me that B.f "is missing a type annotation". It seems obvious to me that B.f has the same types as A.f, especially given that mypy shows me an error if I try to put different ones:

    class B(A):
    def f(self, a: bool) -> str:
    return str(a)


    error: Return type "str" of "f" incompatible with return type "int" in supertype "A" [override]
    error: Argument 1 of "f" is incompatible with supertype "A"; supertype defines the argument type as "int" [override]
    note: This violates the Liskov substitution principle
    note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides


    Since mypy already knows the expected types of B.f, why does it force me to re-declare them? Is there some way to avoid it?

    Continue reading...

Compartilhe esta Página