relative imports and sub-module execution

King animator333 at gmail.com
Mon Sep 27 19:54:28 CEST 2010


Hi,

After reading couple of docs and articles, I have implemented a simple
test package with nested modules.
When running "main.py", everything is working fine. Some of my sub-
modules has some small test routines for debug purpose.
It's because I am using relative package imports at the top, I am not
able to run these sub modules individually.

For example, this works when running from main.py

Here is example structure

main.py
__init__.py
core/
    __init__.py
   folder1
        __init__.py
       f1a.py
       f1b.py
    folder2
        __init__.py
       f2a.py
       f2b.py

in folder2/f2b.py, I am importing

from core.folder1 import f1a
print f1a.myvar

Now I can't execute 'f2b.py' individually. It's giving an error:

ImportError: No module named core.folder2

Is this mean when you have created a package where modules are using
relative imports, they can't execute individually?

Another solution that I have discovered is using sys.path. Check this:

import sys
import os
sys.path.append(os.path.abspath("../../"))
from core.folder1 import f1a
print f1a.myvar

This works fine and easier too. I can execute modules individually as
well as package is also working. Are there any disadvantages when
using above technique? Couple of articles suggests that this is a bad
practice and should not be used.

Need some clarifications.

Thanks

Prashant





More information about the Python-list mailing list