importing a module in nested packages
Solution 1:
What you want is a relative import like:
from ..a.b import module
The problem with this is that it doesn't work if you are calling test_file.py as your main module. As stated here:
Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always "main", modules intended for use as the main module of a Python application should always use absolute imports.
So, if you want to call test_file.py
as your main module, then you should consider changing the structure of your modules and using an absolute import, else just use the relative import from above.
Solution 2:
The directory
a
needs to be a package. Add an__init__.py
file to make it a package, which is a step up from being a simple directory.The directory
b
also needs to be a subpackage ofa
. Add an__init__.py
file.The directory
test
should probably also be a package. Hard to say if this is necessary or not. It's usually a good idea for every directory of Python modules to be a formal package.-
In order to
import
, the package needs to be onsys.path
; this is built from thePYTHONPATH
environment variable. By default the installed site-packages and the current working directory are (effectively) the only two places where a package can be found.That means that
a
must either be installed, or, your current working directory must also be a package one level abovea
.OR, you need to set your
PYTHONPATH
environment variable to includea
.
http://docs.python.org/tutorial/modules.html#the-module-search-path
http://docs.python.org/using/cmdline.html#envvar-PYTHONPATH
Also, http://docs.python.org/library/site.html for complete information on how sys.path
is built.