输入检查 Python class

Type checking in a Python class

我正在尝试使用静态类型检查工具来检查对变量的错误赋值。例如,将一个字符串分配给一个 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'

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

所以当我复制你的代码并用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 代码中,选择 mypy 作为 linter 会在 a 变量下划线并覆盖 mypy 错误。

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

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

You can always use a Python interpreter to run your statically typed programs, even if they have type errors: $ python3 PROGRAM

From the documentation.

我不能代表其他 IDE,但是 Visual Studio 代码(使用 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]