How does Python's module search path and sys.path work?
· Category: Python Programming
Short answer
When you import a module, Python searches the directories listed in sys.path. This list includes the current script's directory, PYTHONPATH, and the standard library site-packages.
Steps
- Check
sys.pathto see where Python looks. - Add custom paths temporarily with
sys.path.append()or permanently viaPYTHONPATH. - Use
-mto run modules and control the first entry insys.path.
import sys
print(sys.path[:3])
# Temporarily add a directory
sys.path.insert(0, "/path/to/modules")
Tips
- The first entry in
sys.pathis usually the directory containing the script or an empty string for the current directory. - Virtual environments modify
sys.pathto prioritize theirsite-packages. - Use
python -m siteto inspect your Python environment's paths. .pthfiles insite-packagescan automatically add directories tosys.path.
import site
print(site.getsitepackages())
Common issues
- Naming a script the same as a standard library module (e.g.,
random.py) shadows the library and breaks imports. - Modifying
sys.pathinside a library affects all downstream imports and can cause unexpected behavior. - Relative imports only work inside packages; running a module as a script breaks relative imports unless using
python -m.