1

我正在尝试使用静态类型检查工具来检查对变量的错误分配。例如,将字符串分配给 int 变量。

我试过pytypemypy。两者都没有给我任何警告。

class A:
    def __init__(self):
        self.x : int = None

if __name__ == '__main__':
    a = A()
    a.x = 'abc'
    print(a.x)

我希望静态类型检查工具可以在上面的行中给我一个警告:

a.x = 'abc'

我是否需要使用一些选项或其他辅助工具来检测这种赋值语句?

4

2 回答 2

1

因此,当我复制您的代码并使用 mypy 进行检查时,会得到以下结果:

project\scratch.py:7: error: Incompatible types in assignment (expression has type "str", variable has type "int")

我通过执行mypy path/to/file.py.

在内部,在 Visual Studio Code 中,选择 mypy 作为 linter 会在a变量下划线并覆盖 mypy 错误。

所以我得到了正确显示的警告错误代码;也许您的 IDE 未设置为处理它们。

注意:执行python path/to/file.py不会显示 mypy 错误,最有可能保持输入 'soft' - 这样代码仍然会执行,而输入更多的是 'hint',而不是停止代码:

你总是可以使用 Python 解释器来运行你的静态类型程序,即使它们有类型错误: $ python3 PROGRAM

从文档中。

于 2019-08-13T04:11:42.903 回答
0

我不能代表其他 IDE,但对于 Visual Studio Code(使用 Python 3.8.5)...

  1. 安装 pylance(微软的 Python 语言服务器扩展)

  2. 将这两行添加到 settings.json:

    "python.languageServer":"Pylance",
    "python.analysis.typeCheckingMode" :"strict"
    
  3. 请注意报告的以下问题:

    (variable) x: None
       Cannot assign member "x" for type "A"
          Expression of type "None" cannot be assigned to member "x" of class "A"
          Type "None" cannot be assigned to type "int"Pylance (reportGeneralTypeIssues) [3, 14]
    
    (variable) x: Literal['abc']
       Cannot assign member "x" for type "A"
          Expression of type "Literal['abc']" cannot be assigned to member "x" of class "A"
          "Literal['abc']" is incompatible with "int"Pylance (reportGeneralTypeIssues) [7, 7]
    
于 2020-08-28T13:06:07.377 回答