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)
This is unfortunately a sys.path hack, but it works quite well.
I encountered this problem with another layer: I already had a module of the specified name, but it was the wrong module.
what I wanted to do was the following (the module I was working from was module3):
Note that I have already installed mymodule, but in my installation I do not have "mymodule1"
and I would get an ImportError because it was trying to import from my installed modules.
I tried to do a sys.path.append, and that didn't work. What did work was a sys.path.insert
So kind of a hack, but got it all to work! So keep in mind, if you want your decision to override other paths then you need to use sys.path.insert(0, pathname) to get it to work! This was a very frustrating sticking point for me, allot of people say to use the "append" function to sys.path, but that doesn't work if you already have a module defined (I find it very strange behavior)
From Python doc,
I think that what you have to ask yourself is:
I don't know the context why you want to do it this way. But for me a cleaner design would be to have the following packages structure:
Then you only have to do:
This is solved 100%:
Import settings/local_setting.py in app/main.py:
main.py:
Let me just put this here for my own reference. I know that it is not good Python code, but I needed a script for a project I was working on and I wanted to put the script in a
scripts
directory.Take a look at http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports. You could do