If you use
import to load a package and subpackage:
import package import package.subpackage
package module instance will contain a
assert "subpackage" in dir(sys.modules['package'])
But if you use Python's
imp module to import these packages instead, the same assertion will fail.
Is this a python documentation oversight, or a bug with the
Clone (or unzip) this repository and then:
python testone.py-- all asserts pass. This tests python's basic
python testtwo.py-- asserts fail, but shouldn't. This uses the
impmodule instead of directly using
import, but it should have the same behavior, I think?
I tested with 2.5, 2.6 and 2.7.
Read the imp module documentation.
The tests can be reconciled as seen in
reconciled.py -- but the documentation doesn't indicate this should be necessary, and it feels like
imp.load_module(...) should manage the content of
sys.modules and the parent module on my behalf.
PS: I found this by investigating mysterious import errors encountered when testing with NoseGAE. NoseGAE uses internal code from App Engine's
dev_appserver.py infrastructure that provides import hooks via
sys.meta_path. Those hooks in turn use the
imp module. Ultimately, this leads to strange import errors. For example, internal Django code will fail to load Django submodules in some cases! The App Engine
HardenedModulesHook class has code that looks like
testtwo.py rather than