问题
I have the following code with python type hints It has a bunch of errors. All erros in code are found by mypy but not the errors in constructor of S. Why? I cannot find out what is happening thanks
code:
import typing
class T(object):
def __init__(self, a: int, b: str = None) -> None:
self.a = a
self.b: typing.Union[str, None] = b
self._callback_map: typing.Dict[str, str] = {}
class S(T):
def __init__(self):
super().__init__(self, 1, 2)
self._callback_map[1] = "TOTO"
s = T(1, 1)
t = T(1, b=2)
t._callback_map[2] = "jj"
s = T(1, 2)
t = T(1, b=2)
t._callback_map[2] = "jj"
output of mypy:
t.py:22: error: Argument 2 to "T" has incompatible type "int"; expected "Optional[str]"
t.py:24: error: Argument "b" to "T" has incompatible type "int"; expected "Optional[str]"
rt.py:25: error: Invalid index type "int" for "Dict[str, str]"; expected type "str"
This is fine, but the same errors (same lines) in 'init' at line 16, 17, 18 are not found at all...
回答1:
Mypy, by default, will only check functions and methods that have type annotations.
Your subclass's constructor has no annotations and so consequently goes unchecked.
To fix this, modify the signature to read def __init__(self) -> None
.
You can also ask mypy to flag these errors for you using the --disallow-untyped-defs
flag. You can also use the --check-untyped-defs
flag which will make it typecheck all functions, whether or not it has annotations.
来源:https://stackoverflow.com/questions/50509163/python-all-type-hints-errors-in-subclass-constructure-seems-ignored