Sub topic 6
How Python finds modules: sys.path
This chapter assumes you can write functions and classes, run scripts from a terminal, and that you know what import does and that imported modules are cached in sys.modules. Here you will learn where Python looks when a module is not yet in that cache.
The search order
When you run import name, Python first checks sys.modules. If the name is missing, Python searches the entries of sys.path, a plain list of strings. Each entry is usually a directory. Python checks them in order and uses the first match.
import sys
for entry in sys.path:
print(repr(entry))The list is built at startup from these sources, in this order:
- The directory of the script you ran. With
python -cor an interactive session, this entry is an empty string or the current directory. Withpython -m, it is the current directory. - Directories listed in the
PYTHONPATHenvironment variable. - The standard library directories.
- The
site-packagesdirectory, where tools such aspipinstall third-party packages.
Built-in modules such as sys are found before any of this, so a file named sys.py cannot replace them.
Why order matters
Because the script's directory comes first, a local file can hide an installed module. Suppose you create random.py next to your script. The statement import random then loads your file, not the standard library. The next chapters on pitfalls return to this problem. For now, avoid naming your files after standard library or installed modules.
You can check which file Python actually loaded:
import json
print(json.__file__)Changing sys.path
You can edit sys.path at runtime, because it is an ordinary list.
import sys
from pathlib import Path
extra = Path("/tmp/my_libs")
sys.path.insert(0, str(extra))
print(sys.path[0])Use insert(0, ...) to take priority over other entries, or append to be searched last. The change affects only the current process and only imports that happen afterward. Modules already in sys.modules are not re-searched.
The PYTHONPATH variable does the same job from outside the program:
# Run in a shell:
# PYTHONPATH=/tmp/my_libs python app.pyEditing sys.path inside code works for quick experiments, but it makes a program depend on hidden paths. For real projects, install your package instead, which a later chapter covers.
Diagnosing ModuleNotFoundError
When an import fails, check these in order:
- Print
sys.pathand confirm the directory containing your module or package is listed. - Confirm you are using the Python interpreter that has the package installed.
sys.executableshows which one is running. - Check the file name and spelling, since the import name must match the file or directory name exactly.
Exercise
You have utils.py in /home/me/project/lib, and you run python /home/me/project/app.py, which contains import utils. The import fails with ModuleNotFoundError. Name two ways to fix it without moving files.
Show answer
Add /home/me/project/lib to the search path. Either set PYTHONPATH=/home/me/project/lib when running the script, or call sys.path.insert(0, "/home/me/project/lib") in app.py before the import. Only the script's own directory, /home/me/project, is searched automatically, so lib is not found.