Python: importing other files into main.py

Hi,
I am trying to split the project into multiple files, but I am getting the following Error: "ModuleNotFoundError: No module named ‘constants’ "
Locally, everything works when I have a second file named “constants.py”, and I import it using “from constants import …”.
Does the test environment for Python not support multiple files?
I hope someone can help, thanks!

Cannot speak about codecrafters’ environment, only from my experience with local environment:

Where is your constants file located? If it’s within the app folder, you may have to do:

from app.constants import ...

For example:

BTW, don’t forget your __init__.py if you’re using mypy.

Thanks for taking the time to answer.
The constants.py and main.py files are both in the app folder.
When I push to the codecrafters test environment, I get the ModuleNotFoundError, so maybe it works differently there?

So all your code is in the app directory. Therefore, when importing constants, the fully qualified import name is app.constants. What you can do is using from app.constants import ... as Andy suggested. Then, you must start your app by using python3 -m app.main (or using your_program.sh)

@isotronic how are you running your app locally btw? On CodeCrafters we use your_program.sh, so it should work the same as long as you’re using that locally too.

I saw another report like this recently, so would love to understand this better and see if there’s anything we can improve

@rohitpaulk I usually just run the main.py directly from the terminal, as I would do that with my scripts outside of codecrafters. For this challenge, I didn’t try using the bash file locally.

1 Like

Gotcha, thanks for sharing!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.