smilebomb smilebomb - 5 months ago 10
Bash Question

Can't find module that exists

From the cli I enter the python shell via

python
.

I then take a look at my import search path:

import sys
print '\n'.join(sys.path)

/path/to/a/package/foo.bar
/other paths...


So I know
foo.bar
is in my python search path.

Continuing inside the python shell:

import imp
imp.find_module('foo.bar')

ImportError: No module named foo.bar


Hmm, the
sys.path
tells me that
foo.bar
is on the python search path, but the
imp
module can't seem to find it.

Continuing further inside the python shell:

from foo.bar import baz
baz

<module 'foo.bar.baz' from '/path/to/a/package/foo.bar/foo/bar/baz.pyc'>


Yes, I have directories
foo
and
bar
under my main directory
foo.bar
. Why would
imp.find_module
not be able to locate my package?

Answer

imp.find_module does not handle names with dots. From the documentation:

This function does not handle hierarchical module names (names containing dots).

It also points out a solution:

In order to find P.M, that is, submodule M of package P, use find_module() and load_module() to find and load package P, and then use find_module() with the path argument set to P.__path__. When P itself has a dotted name, apply this recipe recursively.