I have a file MySQL.py
which contains a class MySQL
defined like so:
class MySQL:
... all stuff that is not important here
In other file (test.py), which is in the same directory I do a conditional loading of this MySQL
class. By this conditional loading I mean, that I load it in case it has not been loaded yet. To check it, I use sys.modules
like so:
print("MySQL" not in sys.modules)
if "MySQL" not in sys.modules:
from MySQL import MySQL
print("Loaded it")
print("MySQL" not in sys.modules)
return MySQL()
As you can see, I have some print's
for debugging purposes. And this is what I get in the console, when I run this file:
$ python3 test.py
True
Loaded it
False
Traceback ...
...
UnboundLocalError: local variable 'MySQL' referenced before assignment
It is really interesting, because in the console we see, that at first the module is not loaded (print("MySQL" not in sys.modules)
=> True
), then we see that it gets loaded, but finally for some crazy reason Python
does not see this class. PS. I should add, that if I import at the very start of my file (before all other code, then everything is ok).
EDIT
I think, I got it, The whole reason of all troubles is that the way I do import
puts my class to sys.modules
, but at the same time it puts it to the local namespace of the function and not the global namespace of the module. That's it.