1

I'm trying to import a function from a file which is in another module but keep getting the following error.

ValueError: Attempted relative import in non-package

I have seen lots of articles saying do absolute instead of relative imports but then get the error

ImportError: No module named app.main.events

My file structure

\_ dir
    \_ __init__.py
    \_ app
        \_ main
            \_ __init__.py
            \_ events.py
        \_ game
            \_ __init__.py
            \_ run.py

events.py

def my_function():
    do something....

run.py

from ..main.events import my_function
# returns
Attempted relative import in non-package

from app.main.events import my_function
# returns
No module named app.main.events

I can't see where im going wrong... It's probably something so simple.

  • Check [this](http://stackoverflow.com/questions/11536764/attempted-relative-import-in-non-package-even-with-init-py) once – Bhargav Rao Dec 11 '14 at 20:06

1 Answers1

0

Relative imports are fine as long as you use them within a package and are explicit, e.g from . import foo. What the articles are saying is bad is when you import foo and rely on a file called foo.py being in the same directory.

If you're executing python run.py directly, the interpreter has no idea that run.py is part of a larger package. You either need to run it as a module using python -m run.main, or preferably (in my opinion) set up an entry point in your setup.py.

Also can't remember if it's necessary or not, but you may be missing an __init__.py in your app subdirectory.

ahal
  • 716
  • 5
  • 6