Class is in sys.modules but cannot be used. Why?
Question: 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.


Answer: Your code doesn't work because if the `MySQL` module has previously been
loaded, you're not importing the class, and so the attempt to call `MySQL()`
on the last line cannot work.

A better approach is to simply do the import unconditionally. Python caches
the module once it's been loaded (this is the whole purpose of `sys.modules`),
so if you import it more than once, the heavyweight code you have in it will
still only be run once.

That said, it may be a sign of bad design if your module is doing a lot of
stuff at the top level. Perhaps you should move some or all of the object
creation or whatever inside a function somewhere and call it at an appropriate
time.

