我尝试使用mypy来检查PyQt5应用程序的代码。但我发现它不会检查我定义的widget类中的代码。我写了一个小的示例应用程序,以找出检查的内容和不检查的内容。
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"
Mypy发现了add_numbers2()
中的类型错误以及主要部分中我尝试将两个整数传递给函数add_numbers()
的错误,该函数仅将字符串作为参数。但由于某种原因,MyWidget.add_number()
和__init__()
函数中的错误已被跳过。 mypy会忽略MyWidget()
类中的所有内容。有人知道如何让mypy完全检查代码吗?
答案 0 :(得分:1)
--check-untyped-defs
调用它。