[Python] Adding __init__.py to make a folder as a package
Adding __init__.py to make a folder as a package
What happened to me
When running my Flask server, I encounter an error: “ModuleNotFoundError: No module named 'server.views'”. Strangely, it worked fine when running python app.py from the command line, but failed in VS Code’s debug mode.
The cause of the issue
-
Python Packages:
A folder is only recognized as a package if it contains an__init__.pyfile. Without it, Python doesn’t treat that folder as an importable module path. -
Working Directory Differences:
Runningpython app.pymanually might set the working directory correctly (soserver/viewsis found).
However, VS Code’s debug mode can start Python in a different folder, so my imports fail if Python can’t locateserveras a package.
The Simple Fixes
-
Add
__init__.pyto every nested directory to import from. For example:project_root/ ├── app.py └── server/ ├── __init__.py # <-- ├── controllers/ │ ├── __init__.py # <-- │ └── user_manager.py └── views/ ├── __init__.py # <-- └── blog.py__init__.pycan be empty—it simply flags the directory as a package. -
Double-check import paths. For example:
from server.views import blogEnsure the folder names match exactly.
-
Run
app.pyfrom the project root folder.# Good cd project_root python app.py # Possibly bad cd project_root/server python ../app.pyThe first approach ensures Python sees
serverat the correct path.
Comments
Post a Comment