3

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?

Community
  • 1
  • 1
LondonRob
  • 73,083
  • 37
  • 144
  • 201
  • Which directory are you in when you are running these commands? – Burhan Khalid Oct 07 '14 at 13:32
  • Good question. I'm either a) at the command line, in the top_module directory or b) in Spyder with top_module directory added to that IDE's "PYTHONPATH manager" tool. – LondonRob Oct 07 '14 at 13:58

2 Answers2

4

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.

LondonRob
  • 73,083
  • 37
  • 144
  • 201
0

Try from sub_module.module_c import *

Undo
  • 25,519
  • 37
  • 106
  • 129