Python packages: relative imports

mgold picture mgold · Apr 8, 2012 · Viewed 7.4k times · Source

I'm working on a Python application consisting of a core and multiple independent modules using the core. I'm having difficulty setting up relative imports of packages.

app
  |- __init__.py
  |- core
        |- __init__.py
        |- corefile.py

  |- module1
        |- __init__.py
        |- main.py

The __init__.py files are empty. I'm running Python 2.7.1.

main.py
from .core import *

Running python main.py results in ValueError: Attempted relative import in non-package.

Similar questions: Ultimate answer to relative python imports, How to do relative imports in Python?, Relative imports in Python

Thanks for the help.

Answer

David Wolever picture David Wolever · Apr 8, 2012

In short, you can only use relative imports from packages that are, themselves, imported.

For example, if you had:

$ cat run.py
from app.module1 import main
main.main()
$ python run.py

Then you could use a relative import in app/module1/main.py (although it would need to be from ..core import foo, because core/ is one level above main.py).