I have defined type hints for the arguments and return values of various methods in my superclass. When I override them in a subclass, should I repeat the same type hints provided in the superclass? Or will they be “inherited” to arguments and return values for the same methods in the subclass?
When you override your function – it is often unclear whether you have broken Liskov substitution principle or not. So let me show you how mypy and pyright (pylance) handle that:
from typing_extensions import reveal_type
class A:
def function(self, a: str, b: int) -> bytes:
...
class B(A):
def function(self, a, b):
...
reveal_type(A().function)
reveal_type(B().function)
mypy (v 0.971) will output:
Revealed type is "def (a: builtins.str, b: builtins.int) -> builtins.bytes"
Revealed type is "def (a: Any, b: Any) -> Any"
pylance (v2022.7.40) will reveal:
Type of "A().function" is "(a: str, b: int) -> bytes"
Type of "B().function" is "(a: str, b: int) -> None"
So mypy will not assume anything and will only look at the hints defined for B.function
while pyright will make assumptions for argument types and assume return type from the source code of the function if there’s no type hint.
So to prevent confusion, I suggest you type hint your overrides
3 Likes