I can’t for the life of me get python’s relative imports to work. I have created a simple example of where it does not function:
The directory structure is:
/__init__.py /start.py /parent.py /sub/__init__.py /sub/relative.py
/start.py contains just:
/sub/relative.py contains just
from .. import parent
All other files are blank.
When executing the following on the command line:
$ cd / $ python start.py
Traceback (most recent call last): File "start.py", line 1, in <module> import sub.relative File "/home/cvondrick/sandbox/sub/relative.py", line 1, in <module> from .. import parent ValueError: Attempted relative import beyond toplevel package
I am using Python 2.6. Why is this the case? How do I make this sandbox example work?
You are importing from package “sub”.
start.py is not itself in a package even if there is a
You would need to start your program from one directory over
./start.py ./pkg/__init__.py ./pkg/parent.py ./pkg/sub/__init__.py ./pkg/sub/relative.py
Now pkg is the top level package and your relative import should work.
If you want to stick with your current layout you can just use
import parent. Because you use
start.py to launch your interpreter, the directory where
start.py is located is in your python path.
parent.py lives there as a separate module.
You can also safely delete the top level
__init__.py, if you don’t import anything into a script further up the directory tree.
If you are going to call
relative.py directly and i.e. if you really want to import from a top level module you have to explicitly add it to the
Here is how it should work:
# Add this line to the beginning of relative.py file import sys sys.path.append('..') # Now you can do imports from one directory top cause it is in the sys.path import parent # And even like this: from parent import Parent
If you think the above can cause some kind of inconsistency you can use this instead:
sys.path.append(sys.path + "/..")
sys.path refers to the path that the entry point was ran from.