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

  1. Check sys.path to see where Python looks.
  2. Add custom paths temporarily with sys.path.append() or permanently via PYTHONPATH.
  3. Use -m to run modules and control the first entry in sys.path.
import sys

print(sys.path[:3])

# Temporarily add a directory
sys.path.insert(0, "/path/to/modules")

Tips

  • The first entry in sys.path is usually the directory containing the script or an empty string for the current directory.
  • Virtual environments modify sys.path to prioritize their site-packages.
  • Use python -m site to inspect your Python environment's paths.
  • .pth files in site-packages can automatically add directories to sys.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.path inside 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.