Module Search Path
2 min read ·
When you import a module, Python needs to locate it. The locations where Python looks for modules are called the module search path.
How Python Finds Modules
When you write an import statement, Python searches in this order:
- Current directory (where your script is located)
- Built-in modules
- Installed packages (site packages directory)
If Python cannot find the module in any of these locations, it raises an error.
Error:
sys.path
Python stores all search locations in a list called
sys.path.This will display all directories where Python looks for modules.
Note
sys.path is just a list, so you can modify it during runtime if needed.
Adding a Custom Path
You can manually add a directory to the module search path.
Caution
Modifying sys.path directly is useful for testing but not recommended for production code.
Current Directory vs Installed Packages
Current Directory
- Python first checks the folder where your script is running
- Useful for user-defined modules
Example:
If
my_module.py is in the same folder, it will be imported successfully.Installed Packages
- Located in site-packages directory
- Installed using pip
Example:
Python finds it inside installed packages.
PYTHONPATH Concept
PYTHONPATH is an environment variable that allows you to add custom directories to Python’s search path.- Works globally
- Avoids modifying sys.path manually
Example (conceptual):
Pro Tip
Use PYTHONPATH when working on large projects with multiple directories.
Important Behavior
- Python stops searching as soon as it finds the module
- First match is used
- Order of paths matters
Exercise
- Print sys.path on your system
- Create a module in a different folder
- Try importing it using sys.path.append()
- Observe how Python locates the module