-2

Unfortunately I get a NameError on reloading a module in Python 2.7.

from PyQt4 import QtCore, QtGui
class MyQThread(QtCore.QThread):
    import foo
    def __init__(self, parent=None):
        super(MyQThread, self).__init__(parent)

    def run(self):
        reload(foo)
        print("Reloaded")
        #...do something

And when I use

thread = MyQThread()
thread.start()

I got this in the shell:

NameError: global name 'foo' is not defined

Any advice?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Mr Pickel
  • 95
  • 10
  • 1
    what is this myModule? – rawwar May 25 '18 at 14:14
  • Why would you ever put an `import` statement in a class? – Aran-Fey May 25 '18 at 14:16
  • @Kalyan: myModule is a name of some example module...I'll change this to foo – Mr Pickel May 25 '18 at 14:16
  • then, that means that, its unable to import that module – rawwar May 25 '18 at 14:17
  • @BartoszKP: sorry for typos. Now the code should work. Unfortunately I can't copy-paste the code. – Mr Pickel May 25 '18 at 14:19
  • Take a look [here](https://stackoverflow.com/questions/707380/in-python-how-can-i-access-static-class-variables-within-class-methods) and then move the `import` into the global scope. – Aran-Fey May 25 '18 at 14:20
  • @Aran-Fey: I've put it there because my thought was to use this class as thread. And after the thread stopped on some action the namespace of import should be cleared (as my understanding of how threading and importing works). – Mr Pickel May 25 '18 at 14:23
  • @MrPickel Surely you can verify what you post before posting, and that's all what this is about. If you don't want to help yourself with Ctrl-C Ctrl-V fine by me :) – BartoszKP May 25 '18 at 14:50

1 Answers1

1

An import statement is a type of assignment. By executing it inside the class statement, you are defining a class attribute named foo that is bound to the module. You would have to use reload(MyQThread.foo).

That said, there is little benefit to putting the import statement in the class definition; just move the import to the global scope.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • I need to import a module by pressing a button inside my GUI. And when it's pressed again the module should be reloaded. How would I achieve that? – Mr Pickel May 25 '18 at 14:30
  • Just as you are doing; I'm saying the *initial* import may as well be outside the class. It will work the same either way, but there should be some significant reason to put the import in a non-standard location. – chepner May 25 '18 at 14:33