简体   繁体   中英

Understanding absolute and relative imports

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.

Relative imports are fine as long as you use them within a package and are explicit, eg from . import foo 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM