tags:

views:

262

answers:

1

Hello, 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: import sub.relative

/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

I get:

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?

+4  A: 

You are importing from package "sub". start.py is not itself in a pcakge even if there is a __init__.py present.

You would need to start your program from one directory over parent.py:

./start.py

./mod/__init__.py
./mod/parent.py
./mod/sub/__init__.py
./mod/sub/relative.py

With start.py:

import mod.sub.relative

Now mod 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.

ebo
You are confusing the terms 'module' and 'package'. 'start.py' represents the module 'start', 'mod' and 'mod.sub' are packages, 'mod' is a toplevel package.
Ferdinand Beyer
Thanks, but this honestly seems really silly. For such a beautiful language, I can't believe the designers would create such a restriction. Isn't there any other way?
carl
It's not silly at all. Relative imports are a mean to refer to sibling modules within a package. If you want to import a toplevel module, use absolute imports.
Ferdinand Beyer
Not silly? So in bash, not been able to address relative upper dir with ".." wouldn't bother you?
e-satis