####Overview
If you use import
to load a package and subpackage:
import package
import package.subpackage
Then the package
module instance will contain a subpackage
attribute:
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 imp
module?
####Instructions
Clone (or unzip) this repository and then:
-
Run
python testone.py
-- all asserts pass. This tests python's basicimport
machinery. -
Run
python testtwo.py
-- asserts fail, but shouldn't. This uses theimp
module instead of directly usingimport
, but it should have the same behavior, I think?
I tested with 2.5, 2.6 and 2.7.
####Notes
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 reconciled.py
.