Import outside toplevel (bad or acceptable?)

Heads up! You've already completed this tutorial.

PedanticHacker | 2021-02-15 17:48:01 UTC | #1

Hello! :)

I have a need (since I'm very pedantic) to fix a thing that Pylint is complaining about in my code.

python
superchess.py
Line: 59
pylint: import-outside-toplevel / Import outside toplevel (source.window.main_window) (col 8)

Please look at my code on GitHub HERE and tell me how can I fix that nagging Pylint message.

I've tried everything and I can't have my code working other than importing main_window inside an if block. I read on some forum that having imports like I do indicate a code smell.

All tries other than what I have now give me this error message: QWidget: Must construct a QApplication before a QWidget

Any help or suggestion would be very welcome. Thanks in advance!

Create GUI Applications with Python & Qt5 by Martin Fitzpatrick — (PyQt5 Edition) The hands-on guide to making apps with Python — Over 10,000 copies sold!

More info Get the book


Eolinwen | 2021-02-25 23:05:39 UTC | #2

Hi, We don't have access to your code on Github (error 404)


PedanticHacker | 2021-02-27 01:25:58 UTC | #3

Yeah, sorry about that. The link works now.

So, what can I do to fix my problem? (The line in question is now 64, not 59.)


martin | 2021-03-05 22:40:33 UTC | #4

The problem is that the import of main_window is creating a QWidget -- you're creating an instance of that window object in that file, which you're then importing -- normally I would import the class, and create the instance of it in this file, e.g.

python
            from source.window import MainWindow  # or whatever it's called
            main_window = MainWindow()
            main_window.show()

That will postpone the creation of the widget til this point, where the QApplication instance exists.


Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak

Import outside toplevel (bad or acceptable?) was written by Martin Fitzpatrick .

Martin Fitzpatrick has been developing Python/Qt apps for 8 years. Building desktop applications to make data-analysis tools more user-friendly, Python was the obvious choice. Starting with Tk, later moving to wxWidgets and finally adopting PyQt.