[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__.py file. Without it, Python doesn’t treat that folder as an importable module path.

  • Working Directory Differences:
    Running python app.py manually might set the working directory correctly (so server/views is found).
    However, VS Code’s debug mode can start Python in a different folder, so my imports fail if Python can’t locate server as a package.

The Simple Fixes

  1. Add __init__.py to 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__.py can be empty—it simply flags the directory as a package.

  2. Double-check import paths. For example:

    from server.views import blog
    

    Ensure the folder names match exactly.

  3. Run app.py from the project root folder.

    # Good
    cd project_root
    python app.py
    
    # Possibly bad
    cd project_root/server
    python ../app.py
    

    The first approach ensures Python sees server at the correct path.

Comments