>我有以下带有python类型提示的代码 它有一堆错误。代码中的所有错误都被 mypy 发现,但 S 的构造函数中的错误没有找到。我无法找出发生了什么 谢谢
法典:
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"中的相同错误(相同的行(......
默认情况下,Mypy 只会检查具有类型注释的函数和方法。
子类的构造函数没有注释,因此未被选中。
要解决此问题,请将签名修改为def __init__(self) -> None
。
您也可以要求 mypy 使用--disallow-untyped-defs
标志为您标记这些错误。您还可以使用--check-untyped-defs
标志,这将使它对所有函数进行类型检查,无论它是否有注释。