How to do relative imports in Python?

Posted by Joril on Stack Overflow See other posts from Stack Overflow or by Joril
Published on 2008-09-16T14:24:02Z Indexed on 2010/04/26 2:03 UTC
Read the original article Hit count: 292

Filed under:

Imagine this directory structure:

app/
   __init__.py
   sub1/
      __init__.py
      mod1.py
   sub2/
      __init__.py
      mod2.py

I'm coding mod1, and I need to import something from mod2. How should I do it?

I tried from ..sub2 import mod2 but I'm getting an "Attempted relative import in non-package".

I googled around but found only "sys.path manipulation" hacks. Isn't there a clean way?


Edit: all my __init__.py's are currently empty

Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (sub1, subX, etc.).

Edit3: The behaviour I'm looking for is the same as described in PEP 366 (thanks John B)

© Stack Overflow or respective owner

Related posts about python