LondonRob
LondonRob

Reputation: 78963

ImportError: No module named '' when importing my own sub-package

By following the instructions in this SO answer I've created a Python package with sub-package as sub-folders, each with a __init__.py file (which are all totally empty).

  top_module
     __init__.py
     module_a.py
        sub_module
             __init__.py
             module_c.py

I can import the top level module but trying to import a sub-module results in an ImportError:

>>> import top_module
>>> import top_module.sub_module
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named sub_module

In iPython I can autocomplete top_model. to show me module_a.py but not sub_module.

Followed the instructions in this SO answer but I just get:

>>> top_module.__file__
'top_module.pyc'

which is not terribly useful. Interestingly, __package__ gives me:

>>> print top_module.__package__
None

I can do this:

>>> import top_module
>>> import sub_module.module_c

So why not import top_module.sub_module.module_c?

Upvotes: 3

Views: 3584

Answers (2)

LondonRob
LondonRob

Reputation: 78963

I've worked out what my problem was (and it's a pretty dumb error I'm afraid.)

I had my PYTHONPATH set to

/path/to/top_module

and was doing

import module_a

which of course worked. But trying to do

import top_module.submodule

didn't work because the PYTHONPATH didn't "know" about top_module, it was already in top_module.

Upvotes: 4

Undo
Undo

Reputation: 25697

Try from sub_module.module_c import *

Upvotes: 0

Related Questions