Back to results for “Debugging”
Python › Modules & Packaging

How does Python locate modules during import, and what is sys.path's role?

Advanced

Answer

When you import a module, Python searches directories listed in sys.path in order: the directory of the script being run (or '' for interactive/current directory), directories from the PYTHONPATH environment variable, and standard installation-dependent paths (including site-packages). The first matching module found wins, which is why sys.path order and accidental name shadowing (e.g., a local file named `json.py`) can cause confusing import bugs.
import sys
print(sys.path)  # list of directories searched, in order

sys.path.insert(0, '/custom/module/location')  # prioritize a custom path
import my_custom_module
Real-world example A developer's script mysteriously imports the wrong `requests` module because a local file named requests.py in the working directory shadows the installed package earlier in sys.path.

Common follow-ups: How do virtual environments modify sys.path?;What's the difference between sys.path and PYTHONPATH?