Python:子类结构中的所有类型提示错误似乎都被忽略了 [英] Python: All type hints errors in subclass constructure seems ignored
问题描述
我有以下带有 python 类型提示的代码它有一堆错误.代码中的所有错误都被 mypy 发现,而不是 S 的构造函数中的错误.为什么?我不知道发生了什么谢谢
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
代码:
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"
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"
这很好,但是在第 16、17、18 行的 'init' 中根本找不到相同的错误(相同的行)...
This is fine, but the same errors (same lines) in 'init' at line 16, 17, 18 are not found at all...
推荐答案
默认情况下,Mypy 只会检查具有类型注释的函数和方法.
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.
要解决此问题,请修改签名以读取 def __init__(self) ->无
.
To fix this, modify the signature to read def __init__(self) -> None
.
您还可以让 mypy 使用 --disallow-untyped-defs
标志为您标记这些错误.您还可以使用 --check-untyped-defs
标志,这将使其对所有函数进行类型检查,无论它是否有注释.
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.
这篇关于Python:子类结构中的所有类型提示错误似乎都被忽略了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!