Description
I wanted to try out the new Python 3.12 typing.override to retire my own implementation, but the bug I had in my code about mismatching return types wouldn't have been caught.
from typing import Dict, Iterable, Union, override
class A:
def f(self) -> Union[Iterable[str], Dict[str, int]]:
return {}
class B(A):
@override
def f(self) -> Union[Iterable[str], Dict[str, str]]:
return {}
Checking this file with pytype test-override.py
prints Success: no errors found
.
I tried to minimize it any further, but taking away anything(!), the Iterable
, the Dict
, the Union
, will correctly result in pytype detecting an error. E.g.:
from typing import Dict, Iterable, Union, override
class A:
def f(self) -> Union[str, Dict[str, int]]:
return {}
class B(A):
@override
def f(self) -> Union[str, Dict[str, str]]:
return {}
and checking with pytype test-override.py
prints:
Computing dependencies
Analyzing 1 sources with 0 local dependencies
ninja: Entering directory `.pytype'
[1/1] check test-override
FAILED: .pytype/pyi/test-override.pyi
/usr/bin/python3 -m pytype.main --imports_info .pytype/imports/test-override.imports --module-name test-override --platform linux -V 3.12 -o .pytype/pyi/test-override.pyi --analyze-annotated --nofail --quick test-override.py
test-override.py:7:5: error: in B: Overriding method signature mismatch [signature-mismatch]
Base signature: 'def A.f(self) -> Union[str, Dict[str, int]]'.
Subclass signature: 'def B.f(self) -> Union[str, Dict[str, str]]'.
Return type mismatch.
def f(self) -> Union[str, Dict[str, str]]:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
return {}
~~~~~~~~~~~~~~~~~
For more details, see https://google.github.io/pytype/errors.html#signature-mismatch
ninja: build stopped: subcommand failed.
Leaving directory '.pytype'
This suggests to me that type hint override checking is something that pytype tries to do, it just does not work in all cases. Note that I also tried very simply type hint override checks with mypy, pylint, pyright and they all don't seem to have function signature checking, so, my thanks go to pytype for at least having some support for that already.
pytype --version # 2024.10.11
python3 --version # Python 3.12.3