relative imports and sub-module execution

Diez B. Roggisch deets at web.de
Tue Sep 28 11:11:29 EDT 2010


King <animator333 at gmail.com> writes:

> 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?

The problem is your python-path. Python will put the path of the script
that you execute into the sys.path - but not attempt to guess that you
actually are deep within a package hierarchy and want the path two up
from there in sys.path as well. Which is the reason why you have to do
that yourself.

My solution to this is to always use setuptools, even for the
tiniest of projects, and simply create a setup.py with some minimal
information in it, and then do

  python setup.py develop

This will put a EGG-link into the site-packages directory. Usually, for
not clobbering my system's python, I use a virtualenv also.

With this setup, I can safely import from "core" all the time.

Diez



More information about the Python-list mailing list