0

So my project structure is:

Application/
    modules/
        classes.py
        game_logic.py
        validations.py
    static/
    templates/
    tests/
        test_classes.py
        test_game.py
    app.py

so the following imports work:

# modules/classes.py:
from modules.validations import validate_word


# modules/game_logic.py:
from modules.validations import validate_word
from modules.classes import Round


# app.py:
from modules.classes import Game
from modules.game_logic import determine_results

However I now need to import to the test_ files the below and I am having trouble:

# tests/test_classes.py:
from modules.classes import Round, Class

# tests/test_game.py:
from modules.game_logic import determine_results

trying the above I get the following error:

E   ModuleNotFoundError: No module named 'modules'

If I add either '..' or '.' preceeding the 'modules' I get the following error:

E   ImportError: attempted relative import with no known parent package

I have now read quite a bit on this and understand that since python 3.3 we have not had to use __init__.py files. I also know that I should be able to get a relative import like that above to work as I have tried it outside of this project. This is a Flask project; would that have anything to do with the problems being experienced?

Chris
  • 13
  • 4
  • See [this post](https://dev.to/methane/don-t-omit-init-py-3hga) about "not required" `__init__.py`. In short, this is so-called "namespace package" which doesn't work as a regular one. It is only important for `pip` packages, not for local usage. You still need `__init__.py` files. And [this question](https://stackoverflow.com/questions/448271/what-is-init-py-for), which is not 100% dupe, but very close to. – STerliakov Jun 30 '22 at 19:45
  • So I have looked at the above linked and added an __init__.py file to the modules folder, with the following code `from .game_logic import *` `from .classes import *`. I then imported in the test_classes.py: `from .modules import Game, Round` and in test_game.py: `from .modules import determine_results`. and whether I add a '.' or not I get no luck and the same error messages in my original post. Did I set this up correctly? – Chris Jul 01 '22 at 18:25

1 Answers1

0

To import the modules to the test_files try this:

from Application.modules.game_logic import determine_results

Application is the directory that contains the modules directory, so you must import from there.

Seraph
  • 374
  • 3
  • 14