我尝试使用 mypy 对 PyQt5 应用程序的代码进行类型检查。但我发现它不会检查我定义的小部件类中的代码。我编写了一个小示例应用程序来找出检查的内容和不检查的内容。
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QGridLayout, \
QSpinBox, QLabel
def add_numbers(a: str, b: str) -> str:
return a + b
def add_numbers2(a: str, b: int) -> int:
return a + b # found: unsupported operand int + str
class MyWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
add_numbers(1, 2) # not found: should result in incompatible type error
self.a_label = QLabel('a:')
self.a_spinbox = QSpinBox()
self.b_label = QLabel('b:')
self.b_spinbox = QSpinBox()
self.c_label = QLabel('c:')
self.c_spinbox = QSpinBox()
self.button = QPushButton('a + b')
layout = QGridLayout()
layout.addWidget(self.a_label, 0, 0)
layout.addWidget(self.a_spinbox, 0, 1)
layout.addWidget(self.b_label, 1, 0)
layout.addWidget(self.b_spinbox, 1, 1)
layout.addWidget(self.button, 2, 1)
layout.addWidget(self.c_label, 3, 0)
layout.addWidget(self.c_spinbox, 3, 1)
self.setLayout(layout)
self.button.clicked.connect(self.add_numbers)
def add_numbers(self):
a = self.a_spinbox.value()
b = self.b_spinbox.value()
c = add_numbers(a, b) # not found: should result in incompatible type error
self.c_spinbox.setValue(c)
if __name__ == '__main__':
add_numbers(1, 2) # found: incompatible type found by mypy
app = QApplication([])
w = MyWidget()
w.show()
app.exec_()
如果我运行 mypy,我会得到以下输出:
$ mypy --ignore-missing-imports --follow-imports=skip test.py
test.py:10: error: Unsupported operand types for + ("str" and "int")
test.py:48: error: Argument 1 to "add_numbers" has incompatible type "int";
expected "str"
test.py:48: error: Argument 2 to "add_numbers" has incompatible type "int";
expected "str"
Mypyadd_numbers2()
在我尝试将两个整数传递给add_numbers()
仅将字符串作为参数的函数的主要部分中发现了类型错误和错误。但是由于某种原因,函数MyWidget.add_number()
中的错误已被跳过。mypy 忽略__init__()
了类中的所有内容。MyWidget()
有人知道如何使 mypy 完全检查代码吗?