Quickly find module to import based on Class name in python

68 views Asked by At

I am learning and playing with Python and Pyside2 (wrapper of QT5).

I am asking about PySide2 but a possible answer could help me with every package.

Basically I am following a tutorial in which I read a portion of code that I am reporting here:

app = QApplication(sys.argv)
pixmap = QPixmap(":/splash.png")
splash = QSplashScreen(pixmap)
splash.show()
app.processEvents()
window = QMainWindow()
window.show()
splash.finish(window)

Since I am a beginner and the tutorial doesn't mention which module I have to import in order to be able to use the QSplashScreen, I am constantly wasting time asking Google on which module I have to import in order to use some method or Class, in this case QSplashScreen.

for example, in order to use a QLabel in my code I have to type

from PySide2.QtWidgets import QLabel

My understanding is that QLabel is "inside" QtWidgets which in turn are "inside" PySide2.

Now my question is if there exist something within Python in such a way that I could do (in a REPL)

import magic
magic.findInTheFollowingPackage("PySide2").somethingINeed("QLabel")
>>> PySide2.QtWidgets # output

Then I could get the answer for

magic.findInThisPackage("PySide2").somethingINeed("QSplashScreen")
1

There are 1 answers

0
alec On BEST ANSWER

You could do something like this:

from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *

def get_import_of(cls):
    print('from', cls.__module__, 'import', cls.__name__)

To print the import statement for any class.

>>> get_import_of(QSplashScreen)
from PySide2.QtWidgets import QSplashScreen

>>> get_import_of(QPixmap)
from PySide2.QtGui import QPixmap

Can extend the function to support multiple arguments:

def get_import_of(*args):
    d = {cls.__module__: [] for cls in args}
    for cls in args:
        d[cls.__module__].append(cls.__name__)
    print('\n'.join(f'from {k} import ' + ', '.join(v) for k, v in d.items()))


>>> get_import_of(QSplashScreen, QPixmap, QLabel, QTimer)
from PySide2.QtWidgets import QSplashScreen, QLabel
from PySide2.QtGui import QPixmap
from PySide2.QtCore import QTimer

Or just type class name into the interactive shell.

>>> QSplashScreen
<class 'PySide2.QtWidgets.QSplashScreen'>