typing: Handling of arguments that can be None

Florian Bruhin me at the-compiler.org
Sun Jul 9 00:23:57 BST 2023


Hey,

In Qt, all arguments are pointers, yet only rarely it's intended usage
to pass a nullptr to functions.

PyQt currently handles this in the type annotations by never using
Optional[...], i.e. always disallowing None.

While this is often the right thing to do, it means that e.g.

    from PyQt6.QtWidgets import QTableView, QApplication
    app = QApplication([])
    tv = QTableView()
    tv.setModel(None)

despite being intended usage. Unfortunately (like here), the Qt
documentation never really points that out:

https://doc.qt.io/qt-6/qabstractitemview.html#setModel

However, the PyQt6-stubs project has gathered a list of known methods
where it's intended usage to pass None for an argument:

https://github.com/python-qt-tools/PyQt6-stubs/blob/main/fixes/annotation_fixes.py#L74

They are:

	- QLineEdit.setText(None)
	- QAbstractItemView.setModel(None) and everything inheriting it
      (QColumnView, QHeaderView, QTableView, QTreeView)
	- QMessageBox.aboutQt(None, ...)  # parent
	- QMessageBox.about(None, ...)  # parent
	- QProgressDialog.setCancelButton(None)

Undoubtedly there will be more yet to be discovered.
But maybe it'd make sense to have some kind of sip annotation (or the existing
/AllowNone/?) so that it generates Optional[...] in the type hints? Then this
could probably be fixed piece by piece when it pops up.

Florian
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20230709/3405addd/attachment.sig>


More information about the PyQt mailing list