views:

137

answers:

2

I am about at wits end with what should be an extremely simple issue. Here is the format of a simple example that I wrote to try to fix my problem. I have a folder top with __all__ = ["p1","p2"] in __init__.py . I then have sub-folders p1 and p2 with __init__.py in both of them with __all__ again defined with the names of two simple module quick1 and quick 2 with quick1 in p1 and quick2 in p2. If I import top.p1.quick1 from a script outside of top then the import works fine. However, trying to import top.p1.quick1 from quick2 gives the error File "quick1.py", line 1, in <module> import top.p2.quick2 ImportError: No module named top.p2.quick2 How can I import a module from another sub-package? This is supposed to work according to the python documentation as far as I can tell. Does anyone see an obvious, trivial mistake that I made?

Edit: It appears that I need to add the directory with top to my search path. I can do this temporarily by setting PYTHONPATH. However, is there a better way to do this from a distutils script?

+2  A: 

Your problem is that your top package is not in your sys.path.

ddaa
Ah.That does seem to be the issue. I can temporarily add the directory to PYTHONPATH, but is there a way to add a directory permanently from distutils? Is there some other preferred way of adding the path?
myurko
+2  A: 

All you describe is just fine and does not reproduce the error -- here's the simplest version I can think of:

$ mkdir /tmp/path
$ mkdir /tmp/path/top /tmp/path/top/p1 /tmp/path/top/p2
$ touch /tmp/path/top/__init__.py /tmp/path/top/p1/__init__.py /tmp/path/top/p2/__init__.py
$ touch /tmp/path/top/p1/quick1.py /tmp/path/top/p2/quick2.py$ echo 'import top.p1.quick1' > /tmp/path/top/p2/quick2.py
$ PYTHONPATH=/tmp/path python /tmp/path/top/p2/quick2.py
$ python -c 'import sys; sys.path.append("/tmp/path"); import top.p2.quick2'

and it runs just fine. The __all__ are not relevant unless you're using from ... import * which you aren't (and right you are not to). As long as the parent directory of top (here, /tmp/path) is on sys.path, things will be fine; if that parent directory is not there, you'll get an error.

So what's the minimal change you can make to this sequence of operations to reproduce the error you observe?

Alex Martelli
I think his minimal change would be to change the last line to:`echo 'import top.p2.quick2' > /tmp/path/top/p1/quick1.py; python /tmp/path/top/p1/quick1.py`
Singletoned
That would be one possible bug, yes -- one simple way of breaking the "As long as the parent directory of top (here, /tmp/path) is on sys.path" condition (to quote my answer -- ddaa's answer mentions it too). There are other bugs that could break that condition, though (putting `/tmp/path/top` in lieu of `/tmp/path` in `sys.path` is one bug frequently observed in the wild, for example -- a parent vs child confusion).
Alex Martelli