relative imports and sub-module execution
Diez B. Roggisch
deets at web.de
Tue Sep 28 17:11:29 CEST 2010
King <animator333 at gmail.com> writes:
> 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
> 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
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.
More information about the Python-list