pythonpython-typingpyside6

How can I override a method where the ellipsis is assigned as the default value of a parameter in python?


In Python v3.10, the following code generates a Pylance error stating (Expression of type "EllipsisType" cannot be assigned to parameter of type "int")

from typing import Any
from PySide6.QtGui import QStandardItem


class A(QStandardItem):
    def data(self, role: int = ...) -> Any:
        return super().data(role)
    pass

In QtGui.pyi, The data method of QStandardItem is defined as follows

def data(self, role: int = ...) -> Any: ...

What is the correct way to subclass by specifying the typing accurately


Solution

  • ... as the default value in a .pyi file does not mean a literal Ellipsis object.

    Rather, role: int = ... means that the parameter role is of type int and has a default value of that same type at runtime, but that value is omitted in the stub file.

    That said, you need to provide a default value of your own:

    class A(QStandardItem):
        def data(self, role: int = 42) -> Any:
            return super().data(role)
    

    If you don't care about LSP, just throw it away entirely:

    class A(QStandardItem):
        def data(self, role: int) -> Any:
            return super().data(role)
    

    Using None or a similar sentinel value is another choice:

    class A(QStandardItem):
        def data(self, role: int | None = None) -> Any:
            if role is None:
                return super().data()
    
            return super().data(role)
    

    I don't know PySide6, so take this with a grain of salt.