I’m trying to understand the difference between a loaded module vs. an imported module, if there is any.
I’m working in Python 2.7.3, and am just running Python from the command line.
If I execute:
import sys
sys.modules
I get a list which includes os, for example. The documentation says that sys.modules is a list of “loaded” modules. However, if I try to run something like os.environ, I get a NameError which tells me that os is not defined. However, if I then run import os, this resolves the issue. Can anyone explain why os exists in sys.modules prior to me actually importing the module?
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 namesyntax (you’ll be able to access the specified name, but not the module itself).You’re seeing the
osmodule in thesys.modulesdictionary 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:
You’ll now be able to access the
osmodule just as if you had doneimport os.That’s because that code is exactly what an
importstatement 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 thesys.modulesdictionary). Theimportstatement 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.