Say I import a module as follows:
import os as OSMOD
and then wanted to find the working directory
OSMOD.getcwd()
OSMOD is now a stand in for os, and using os won't work. This is all dandy, and works for me. However, I noticed something a little odd. If I import os as I do above, and then get a list of all imported modules, here's what happens:
>>> import sys
>>> import os as OSMOD
>>> modList = sys.modules.keys()
>>> print "os" in modList
True
>>> print "OSMOD" in modList
False
This is not what I expected. According to the docs modules.keys() only lists the imported modules. To me, this means it should list OSMOD.
Why doesn't sys.modules.keys() contain OSMOD instead of os?
Additionally, is there an equivalent list to sys.modules.keys() which would contain OSMOD?
EDIT: I guess the larger question here is the rationale. If Python is going to keep os as the module, why delete the reference? (ie, why don't both os.getcwd() and OSMOD.getcwd() work?)
Or, more simply put, why doesn't import os as OSMOD behave the same as import os followed by OSMOD = os?
Because the name of the module is os. You did import os. as OSMOD just tells Python to assign that module to the name OSMOD in your module's namespace.
sys.modules is a cache of imported modules to prevent modules from being imported more than once. If it stored the imported module under OSMOD, another module that did import os would import the module again.
You seem to be confused about the module object and the references to that object. sys.modules['os'] is one reference to the module object, and OSMOD is another.
When you use the statement import os as OSMOD, Python makes sure the os module is loaded into memory (using the sys.modules dictionary as a cache) then creates a reference to the module object in your current namespace. Because you used as OSMOD Python sees that you want to use the name OSMOD and binds the module to that name.
Had you used import os, then Python would have defaulted to the same name as the module, so it binds the object to os in your local namespace.
You are in no way restricted here. You can still bind the same object to other names too:
os = OSMOD
would give you another reference to the same module object.
Remember that your module global namespace is only global to the module; other modules don't see the same names. As such you want to control what names are defined in it. Perhaps you wanted use the name os for something else entirely. The following is legal:
os = 'Ozzy Santana'
import os as OSMOD
and I would expect os to still be bound to the string, not the module.
At the same time, another module in my Python project can still use import os and have os refer to the module; it won't see the string bound to os in the first module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With