Relative Imports, why the hell is it so hard?

Maxim Khitrov mkhitrov at gmail.com
Mon Mar 23 16:50:22 CET 2009


On Mon, Mar 23, 2009 at 11:22 AM, CinnamonDonkey
<CinnamonDonkey at googlemail.com> wrote:
> 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.

That is correct, but you cannot jump beyond the parent package, which
is why your code isn't working.

> 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 :-)
> Cheers!

Sorry, I use that line to avoid conflicts with standard modules, and
forgot that relative imports are already enabled.

Basically, the reason your code doesn't work is because you're trying
to use relative imports between two separate packages. As far as I
know, this isn't possible. What I did to get your code working was
move main.py one directory up and create an empty __init__.py under
\App. The following code should then work:

# main.py
import App.subpack1.module1

if __name__ == "__main__":
   App.subpack1.module1.subpack1_module1_foo()

# App.subpack1.module1
from ..subpack2 import module2

def subpack1_module1_foo():
   print "subpack1_module1_foo()"
   call_subpack2_module1()

def call_subpack2_module1():
   module2.subpack2_module2_foo()

# App.subpack2.module2
def subpack2_module2_foo():
   print "subpack2_module2_foo()"

- Max



More information about the Python-list mailing list