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.

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!

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.

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

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

1:1 Coaching & Tutoring for your Python GUIs project
Martin Fitzpatrick Python GUIs Coaching & Training
60 mins ($195) More info 120 mins ($375)

1:1 Python GUIs Coaching & Training

Comprehensive code reviewBugfixes & improvements • Maintainability advice and architecture improvements • Design and usability assessment • Suggestions and tips to expand your knowledgePackaging and distribution help for Windows, Mac & Linux • Find out more.

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.

Interested in contributing to the site? Find out more.