Python's import system is powerful, but it can sometimes trip up even experienced developers with the dreaded ModuleNotFoundError
. This guide explains why this error occurs and walks you through a real-world scenario to quickly resolve it.
The Problem: ModuleNotFoundError When Importing Local Files
Imagine you have the following project structure:
my_project/
├── main.py
└── utils/
└── helper.py
You want to use a function from helper.py
in main.py
. Naturally, you might write:
# main.py
from helper import useful_function
useful_function()
But running python main.py
leads to:
ModuleNotFoundError: No module named 'helper'
Why Does This Happen?
Python’s import system searches for modules in directories listed in sys.path
, which includes the current directory and installed packages. By default, it does not look inside subfolders unless they're treated as packages.
The Solution: Correctly Importing from Submodules
Step 1: Make utils
a package by adding an empty __init__.py
file:
my_project/
├── main.py
└── utils/
├── __init__.py
└── helper.py
Step 2: Update the import statement in main.py
to reference the package:
# main.py
from utils.helper import useful_function
useful_function()
Step 3: Run your script as a module from the project root:
python -m main
or, if main.py
is the top-level script:
python main.py
Key Takeaways
- Local modules in subfolders must be imported using the package path (e.g.,
from utils.helper import ...
). - Always include an
__init__.py
file in directories to mark them as Python packages. - Check your current working directory and run scripts from the project root for imports to resolve properly.
By understanding Python’s import mechanics and structuring your project as a package, you’ll avoid most ModuleNotFoundError
headaches and write cleaner, more maintainable code.