smilebomb
smilebomb

Reputation: 5493

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?

Upvotes: 0

Views: 951

Answers (2)

syntonym
syntonym

Reputation: 7384

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.

Upvotes: 1

ismail
ismail

Reputation: 185

  • Don't have a . in the folder name.
  • Make sure there is an empty __init__.py file in the foo & bar folders. This is required for python to see it as a package
  • Make sure the folder that the foo folder is in, is in sys.path

Upvotes: 0

Related Questions