Python sys.modules contains a module which is not yet imported
The difference between a module being imported and being loaded is what is placed into your current module's namespace. A module will only get loaded once (in ordinary situations), but can be imported many times, from many different places. A loaded module may not be accessible in a given namespace, if it hasn't been imported there. For instance, you can load a module without importing it under its name using the from module import name
syntax (you'll be able to access the specified name, but not the module itself).
You're seeing the os
module in the sys.modules
dictionary because it's used internally by the python interpreter, and so it is always loaded at startup. You can't access it using the name "os" though, because it isn't automatically imported into your namespace.
However, you can bypass the normal import mechanisms in a few ways. For instance, try this:
import sys
os = sys.modules["os"]
You'll now be able to access the os
module just as if you had done import os
.
That's because that code is exactly what an import
statement does when you request a module that has already been loaded. However, if you try the code above with a module that isn't loaded yet, it won't work (you'll get a key error from the sys.modules
dictionary). The import
statement loads new modules in addition to adding them to the current namespace. While you can manually load modules and further work around the regular import system, there's rarely a good reason to do so.