mypy 无法识别函数中发生的键入错误

问题描述 投票:0回答:1

当我有这样的代码时:

class C : pass

def f1( c : C ) : pass

f1( 100)

def f2( c : C = None ) : pass

f2( 100)

然后 mypy 声明这样的错误:

$ mypy 002_1.py 
002_1.py:11: error: Argument 1 to "f1" has incompatible type "int"; expected "C"
002_1.py:15: error: Argument 1 to "f2" has incompatible type "int"; expected "Optional[C]"
Found 2 errors in 1 file (checked 1 source file)

这是预期的。

但是当我有这样的代码时:

class C : pass

def f1( c : C ) : pass

def f2( c : C = None ) : pass

def test001() :
 f1( 100)
 f2( 100)

test001()

然后 mypy 看不到错误。

我正在使用 mypy 0.812 和 Python 3.9.2。

我该怎么做才能看到打字错误?

提前致谢。

python python-3.x function mypy typechecking
1个回答
0
投票

您所观察到的行为的发生是因为 mypy 对缺少类型注释的函数内部的类型检查不太严格。默认情况下,mypy 重点检查函数签名,而不是未注释函数中的代码。这就是当函数调用位于

test001()
内部时不会报告错误的原因。 要引发错误,您可以向 test001() 函数添加类型注释 就像
None
。您可以在 mypy 中手动启用严格模式,这将有助于通过强制执行更严格的类型检查来解决问题,包括在缺少类型注释的函数体内。
mypy --strict 002_1.py
。 您可以将
--disallow-untyped-defs
选项与 mypy 一起使用,也可以通过要求所有函数签名的类型注释来解决问题。启用此选项后,mypy 将标记任何没有类型注释的函数,迫使您显式注释每个函数。

mypy --disallow-untyped-defs 002_1.py```

Or (`--check-untyped-defs`)[https://mypy.readthedocs.io/en/stable/command_line.html]which checks the bodies of functions without type annotations.It type checks the body of every function, regardless of whether it has type annotations. (By default the bodies of functions without annotations are not type checked.)



© www.soinside.com 2019 - 2024. All rights reserved.