12
votes

Possible Duplicate:
How to properly use relative or absolute imports in Python modules?

I have this file layout, as shown in this example: (download here: http://www.mediafire.com/?oug42nzvxrvoms4) http://www.python.org/dev/peps/pep-0328/#guido-s-decision

moduleX contains:

from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo
from ...package import bar
from ...sys import path

and this is what happens:

C:\package\subpackage1>python moduleX.py
Traceback (most recent call last):
  File "moduleX.py", line 1, in <module>
    from .moduleY import spam
ValueError: Attempted relative import in non-package

I have python 2.7.2. I have

__init__.py

files in every directory. Why does this code not work?

1
I find this Q&A more useful than the one this has been marked a duplicate of.ArtOfWarfare
Robot duplicate taggers ;-)nicorellius

1 Answers

22
votes

From the docs:

you can see this:

Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

By running it as python moduleX.py, you are doing exactly the above. Instead, try this:

python -m package.subpackage1.moduleX

This will import moduleX and put the top level at package. Run from the top of the hierarchy:

package/
    __init__.py
    subpackage1/
        __init__.py
        moduleX.py
        moduleY.py
    subpackage2/
        __init__.py
        moduleZ.py
    moduleA.py

i.e. in your case from c:\ directly:

c:\>python -m package.subpackage1.moduleX

Note one thing - the imports in moduleX.py are these:

from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo
from ...package import bar
from ...sys import path

The second to last:

from ...package import bar

requires the root folder (c:\ in your case) to be a package (i.e. have __init__.py). Also, it requires bar variable defined in package\__init__.py, which is currently not there (so put bar = 'bar!' there for test). It also requires you to be one level up - so you have to put the package folder in another folder (so you end up with c:\toppackage\package) and run c:\python -m toppackage.package.subpackage1.moduleX.

For this line:

from ...sys import path

there's a note in the above PEP 328 link:

Note that while that last case is legal, it is certainly discouraged ("insane" was the word Guido used).

See also other SOqs about this that might help:

Hope this helps.