Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I @override the following @overloaded Python function?

The PySide6 function QComboBox.addItem is type-hinted, in QtWidgets.pyi, like this:

@overload
def addItem(self, icon: Union[PySide6.QtGui.QIcon, PySide6.QtGui.QPixmap], text: str, userData: Any = ...) -> None: ...
@overload
def addItem(self, text: str, userData: Any = ...) -> None: ...

In order to cleanly (according to type checkers) @override it, I need to provide a Python implementation which "accepts all possible arguments of" signatures 1 and 2, yet I seem unable to do so not least due to the fact that the text argument appears in different positions.

What are strategies to deal with this?

like image 212
bers Avatar asked Oct 31 '25 18:10

bers


1 Answers

Yes, but @override should only need to be added on the implementation, not the @overloads.

import typing_extensions as typing

import PyQt5.QtGui
import PyQt5.QtWidgets

class MyQComboBox(PyQt5.QtWidgets.QComboBox):

    @typing.overload
    def addItem(self, text: str, userData: typing.Any = ...) -> None: ...

    @typing.overload
    def addItem(self, icon: PyQt5.QtGui.QIcon, text: str, userData: typing.Any = ...) -> None: ...

    @typing.override
    def addItem(self, *args: object, **kwargs: object) -> None:
        """
        Your implementation. `*args` and `**kwargs` are just
        placeholders for the signature you actually want.
        """
$ mypy test.py
Success: no issues found in 1 source file

For mypy to stop complaining about overridden @overloaded methods in a subclass you need to copy all overloads over (as with the example above). This is unergonomic and error-prone. In my opinion, you should just implement the signature(s) you want to accept for the overridden method in the subclass, and suppress warnings for @overload issues with # type: ignore.

like image 147
dROOOze Avatar answered Nov 03 '25 08:11

dROOOze