2

I'm trying to use the inspect module to determine the Signature of methods and I'm running into a problem with PyQt widgets. The widgets report a signature containing *args and **kwargs, but cannot be called with arbitrary keyword arguments:

>>> from PyQt5.QtWidgets import QWidget, QApplication
>>> from inspect import signature
>>> signature(QWidget.__init__)
<Signature (self, /, *args, **kwargs)>
>>> app = QApplication([])
>>> QWidget(c=10)
TypeError: 'c' is an unknown keyword argument

However, VSCode seems to be able to tell what the actual signature of the method is, as it correctly autofills calls or overrides:

QWidget(

shows the following tooltip: enter image description here

and:

class MyWidget(QWidget):
    def __init__

autocompletes the overriden __init__ method to:

def __init__(self, parent: ,, flags: ,) -> None:
    super().__init__(parent=parent, flags=flags)

Is there a way I can actually get this correct signature of PyQt5's widget methods in my code?

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Mate de Vita
  • 1,102
  • 12
  • 32

1 Answers1

2

It appears the simplest soultion is to use the doc-string:

>>> QWidget.__doc__
'QWidget(parent: QWidget = None, flags: Union[Qt.WindowFlags, Qt.WindowType] = Qt.WindowFlags())'
>>>
>>> QWidget.windowTitle.__doc__
'windowTitle(self) -> str'

I'm not sure where VSCode gets its signature from. Some IDEs (like PyCharm) use typehint stub files for code-completion and call-tips - but this issue seems to suggest VSCode may not do that (yet).

As for inspect.signature: the note in the docs strongly suggests this won't always work with extension modules. It doesn't even work consistently with the python built-ins:

>>> inspect.signature(list)
<Signature (iterable=(), /)>   
>>>
>>> inspect.signature(dict)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.9/inspect.py", line 3130, in signature
    return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
  File "/usr/lib/python3.9/inspect.py", line 2879, in from_callable
    return _signature_from_callable(obj, sigcls=cls,
  File "/usr/lib/python3.9/inspect.py", line 2410, in _signature_from_callable
    raise ValueError(
ValueError: no signature found for builtin type <class 'dict'>
ekhumoro
  • 115,249
  • 20
  • 229
  • 336