ModuleNotFoundError
in Python Package Imports
You have a Python package folder Demo_Project
with two files:
from_keyword_demo.py
math_functions.py
Inside from_keyword_demo.py
, you have this import line:
from math_functions import addition
But when you run import Demo_Project.from_keyword_demo
in another script or interactive shell, you get this error:
ModuleNotFoundError: No module named 'math_functions'
This means Python cannot find math_functions.py
as a top-level module outside your package.
When you write from math_functions import addition
inside from_keyword_demo.py
, Python interprets math_functions
as a top-level module.
But since math_functions.py
is inside the Demo_Project
folder (a package), Python doesn't find it in the global module search path.
Summary: Your import statement is not βpackage-awareβ and should specify it is importing within the same package.
Prefix the module name with a dot .
to indicate it's relative to the current package:
from .math_functions import addition
This tells Python: look inside the current package folder for math_functions.py.
Explicitly import using the full package path from the project root:
from Demo_Project.math_functions import addition
This approach requires your project folder (the one containing Demo_Project
) to be on Python's PYTHONPATH
or the current working directory.
Your folder should look like this to behave as a proper package:
Demo_Project/
βββ __init__.py # Makes Python treat this as a package
βββ from_keyword_demo.py # Your script importing math_functions
βββ math_functions.py # The module containing functions like addition
Note: The __init__.py
can be empty, but it is essential for Python versions before 3.3 to recognize folders as packages.
Don't run package modules directly using:
python from_keyword_demo.py
Running like this treats from_keyword_demo.py
as a standalone script and breaks relative imports.
Instead, run your module as part of the package with the -m
switch from the folder above Demo_Project
:
python -m Demo_Project.from_keyword_demo
This runs the module with the correct package context so relative imports work perfectly.
Concept | Recommended Practice | Notes |
---|---|---|
In-package imports | from .module import name (relative) or from package.module import name (absolute) |
Relative imports are easier to maintain when moving code inside packages. |
Execution method | Use python -m package.module from the parent directory of your package |
Direct script runs break relative imports and cause module not found errors. |
Package structure | Include __init__.py file in folders to mark packages |
Essential for older Python versions and to avoid import issues. |
Common mistakes | Using top-level imports inside package modules without relative notation | Causes Python to look outside the package folder for modules. |