3

Consider the following code:

enter image description here

PyCharm automatically senses that this is a module that could refer to one or more backing libraries.

Is it possible to specify this manually for other module variables as well? Something like the following:

from pyqtgraph.Qt import QtWidgets
QtWidgets: Union[PyQt5.QtWidgets.pyi, PySide2.QtWidgets.pyi] # <-- I want to add this type hint

Behind the scenes, pyqtgraph is dynamically constructing dummy QtWidgets to point to one of several libraries at runtime, but PyCharm doesn't know this. Is there a way for me to manually add that type hint (QtWidgets.pyi) to a module that I import (In this case, pyqtgraph.Qt.QtWidgets)?

I posted here as well, for reference.

ntjess
  • 570
  • 6
  • 10

1 Answers1

2

enter image description here

As you can see here, it doesn't show me hints for sys.Test, as it doesn't exist. What you can do - you can use Stubs, aka .pyi files. i just added a sys.pyi file, [it must be named the same as your module, pyqtgraph.pyi in your case]. it doesn't evaluate the file but uses it to gather type hintings. the result is enter image description here

And the content of sys.pyi is:

Test: bytes

You can read about stubs, Here: https://www.jetbrains.com/help/pycharm/stubs.html

Jonathan1609
  • 1,809
  • 1
  • 5
  • 22
  • 1
    This works, thanks! I combined it with https://stackoverflow.com/a/63552927/9463643 to avoid stubbing the entire library, so I just added your pyi solution to the dynamic module. – ntjess Jun 30 '21 at 19:45
  • Edit: The linked SO post doesn't actually provide intellisense for the remaining methods -- it just keeps PyCharm from raising errors... Looks like stubs have to be defined nowhere or everywhere, then... Following https://youtrack.jetbrains.com/issue/PY-46104 – ntjess Jun 30 '21 at 20:34
  • Stubs are just being used for type hinting, they don't get executed anywhere. – Jonathan1609 Jun 30 '21 at 20:35
  • Right -- but currently in PyCharm if you add stubs for a single submodule, PyCharm expects you to provide stubs for everything else otherwise it breaks all remaining code completion – ntjess Jun 30 '21 at 20:39
  • WOW, i didn't know that, mine works perfectly as it searches for .pyi files, and if it doesn't find any for a particular module that it just uses the normal .py files to gather the type hinting from. anyway thanks for acknowledging! – Jonathan1609 Jun 30 '21 at 20:40