Relative Imports, why the hell is it so hard?
CinnamonDonkey at googlemail.com
Mon Mar 23 16:22:21 CET 2009
Thanx for the quick responses, it is very much appreciated!
Skip, that's a good point about "C++ != Python" and I assure you I am
very much aware of that ;-).
Looking at http://www.python.org/dev/peps/pep-0328/#guido-s-decision
would suggest, unless I am completely miss-understanding the example,
that '.' refers to the current level and '..' pops up a level. First
# Access moduleY in same level as ModuleX
from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
Just to be sure though I tried both ;):
from ..subpack2 import module1 #ValueError: Attempted relative import
beyond toplevel package
from .subpack2 import module1 #ImportError: No module named subpack2
from . import subpack2 #ImportError: cannot import name subpack2
from .. import subpack2 #ValueError: Attempted relative import beyond
Max, thank you for the response... I tried adding "from __future__
import absolute_import" which made no difference. I still get exactly
the same error messages. Perhaps I should have mentioned that I am
using Python 2.5, which I understand alread supports relative imports
out of the box. I'll keep this line in for now anyway though :-)
from __future__ import absolute_import
from .. import subpack2
if __name__ == "__main__":
I am starting the sandbox app with the command line: python main.py
with the current working directory in \app where main.py is located.
On 23 Mar, 14:44, s... at pobox.com wrote:
> >> Please, please... please! don't go off on rants about why you think
> >> relative imports should not be used. I've got 15+ years in C++ and
> >> relative inclusion of other sections of code has never been a
> >> problem. As far as I am concerned what I am trying to do is
> >> perfectly reasonable and valid.
> However, C++ != Python. Regardless whether or not you can "make it work",
> translating idioms from one language to another is often suboptimal. That
> may not be the case here, but it bears keeping in mind.
> >> Example:
> >> \ App
> >> | main.py
> >> +--\subpack1
> >> | | __init__.py
> >> | | module1.py
> >> |
> >> +--\subpack2
> >> | | __init__.py
> >> | | module2.py
> >> Module1 needs to access functionality in Module2.
> >> #module1.py
> >> from ..subpack2 import module2
> >> Seems reasonable to me... but it just does not work and I was so
> >> liking Python. :(
> You might try removing a dot from your import statement. Python is also not
> Unix. Popping up one level in the package hierarchy is done with ".", not
> Skip Montanaro - s... at pobox.com -http://www.smontanaro.net/
More information about the Python-list