0

I tried to restructure my project for my own Tetris. With changing it to different files and also different folders I got confused about the module imports.

This is the directory

Jstris
├── code_base
│   ├── constants.py
│   ├── functions.py
│   └── tetromino.py
│       
├── game_mode
│   ├── free_play.py
│   └── sprint.py
└── run.py

The main goal is to execute the run.py file and it works as it should. Just to be clear, the whole game is working. I get to a menu and can start all my different games. But I want to understand what is happening here and can't figure it out myself.

In run.py I import e.g.: (not the original code, just for demonstration)

from code_base.constants import SCREEN_HEIGHT, SCREEN_WIDTH
from code_base.functions import draw_window
from game_mode.free_play import main_free_play

In functions.py I import the following:

from code_base.constants import PLAY_WIDTH, PLAY_HEIGHT
from code_base.tetromino import Tetromino

I need to have the syntax like above in functions.py to not get an error when executing run.py. But if I want to execute functions.py I get an error "ModuleNotFoundError: No module named 'code_base'.

Do I have to accept it because I won't ever execute functions.py or is there a way my whole projects works but still every module itself is able to work fine when executing ? Or one step further, is my way to structure the files and the importing just circuitous/ not Python convention? I'm using python 3.8

Rabinzel
  • 7,757
  • 3
  • 10
  • 30

1 Answers1

0

this is because of relative path, when you run your "run.py" file, it understand code_base.functions because it sees 2 modules (code_base and game_mode), which are your folder names in Jstris folder, but when you import the same name in functions.py it looks for a code_base folder and doesn't find one, so it raises an error if you want all your modules to run by themselves, you can try absolute paths, which is covered in this issue : How to import a module given the full path?

fmansour
  • 555
  • 3
  • 17
  • ok, I think i got that. Thanks for the link! So as a conclusion, is it appropriate python style/code to have a run.py file which is connected to all the other files and works - and at the same time single files in subdirectorys can't be executed by themselves? – Rabinzel Oct 02 '21 at 12:01
  • in your case I think yes, you have a game that uses several utilities and functions, these functions are just for import and they are being used in other apps (they don't do something by their own), so if you need them you just import them once again (reuse them) – fmansour Oct 02 '21 at 12:04
  • ok, good. thank you ! – Rabinzel Oct 02 '21 at 12:37