简体   繁体   中英

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 ?

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 .

尝试from sub_module.module_c import *

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM