简体   繁体   中英

Python module not found because import statement is in other file than the one being executed

In the following structure:

src:
    model:
        - boardmodel.py
        - tests.py
        exceptions:
            - exceptions.py
    - visual.py

I'm running visual.py from the terminal. In my boardmodel.py , I have the following import:

from exceptions.exceptions import ZeroError, OverlapError, ArgumentError, ProximityError

This line causes an error when running visual.py :

Traceback (most recent call last):
  File "visual.py", line 3, in <module>
    from model.boardModel import Board
  File "/Users/sahandzarrinkoub/Documents/Programming/pythonfun/BouncingBalls/balls/src/model/boardModel.py", line 5, in <module>
    from exceptions.exceptions import ZeroError, OverlapError, ArgumentError, ProximityError
ModuleNotFoundError: No module named 'exceptions'

What is the correct way to solve this problem? Should I change the import statement inside boardmodel.py to from model.exceptions.exceptions import ZeroError.... ? That doesn't feel like a sustainable solution, because what if I want to use boardmodel.py in another context? Let me her your thoughts.

EDIT:

I changed the structure to:

src:
    model:
        - __init__.py
        - boardmodel.py
        - tests.py
        exceptions:
            - __init__.py
            - exceptions.py
    - visual.py

But still I get the same error.

Place an empty file called __init__.py in each of the subdirectories to make them packages.

See What is __init__.py for? for more details

Then, within boardmodel.py you need to either use relative imports

from .exceptions.exceptions import ...

or absolute ones (from the root of PYTHONPATH)

from model.exceptions.exceptions import ...

When you execute a script from the command line, the directory containing the script is automatically added to your PYTHONPATH , and becomes the root for import statements

You are not at the root of your package so you need relative import.

Add a dot before exceptions :

from .exceptions.exceptions import ZeroError, OverlapError, ArgumentError, ProximityError

One dot mean "from the current directory"…

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