Sub topic 6
How Python finds modules: sys.path
This chapter assumes you can write functions and classes, run scripts from a terminal, and have read the earlier chapters on what happens when you import. You already know that import first checks the sys.modules cache. Here we cover what happens on a cache miss: where Python looks, in what order, and why it sometimes looks in the wrong place.
The search order
When a module name is not in sys.modules, Python searches for it in this order:
- Built-in modules compiled into the interpreter, such as
sysandbuiltins. The names are listed insys.builtin_module_names. - The entries of
sys.path, from first to last.
The first match wins. Python stops at that match, even if a better module with the same name appears later in the list.
What sys.path is
sys.path is an ordinary Python list of strings. Each string is a place to search, usually a directory. It can also be a .zip file.
import sys
for entry in sys.path:
print(repr(entry))The output differs on every machine. A typical result has these parts, in this order:
- The script directory, or an empty string when you run an interactive session.
- Entries from the
PYTHONPATHenvironment variable. - The standard library directories.
- The
site-packagesdirectory, wherepipinstalls third-party packages.
Where the first entry comes from
The first entry depends on how you start Python. This is the most common source of confusion.
| How you start Python | First `sys.path` entry |
|---|---|
| `python script.py` | The directory that contains `script.py` |
| `python -m package.module` | The current working directory |
| `python` (interactive) | An empty string, meaning the current directory |
| `python -c "..."` | An empty string, meaning the current directory |
The directory of the script is not the same as your current working directory. If you run python src/app.py from your home directory, Python searches src/, not your home directory. Running the same file with python -m searches the working directory instead.
In Python 3.11 and later, the -P option and the PYTHONSAFEPATH environment variable stop Python from adding this first entry. This is useful for security-sensitive tools, because a stray file in the current directory can no longer shadow a real module.
Seeing the search in action
Create two files in the same directory.
# helper.py
print("helper loaded from", __file__)
VALUE = 42# main.py
import sys
import helper
print(sys.path[0])
print(helper.VALUE)
print(helper.__file__)Running python main.py works because main.py's directory is sys.path[0], and helper.py lives there. Move helper.py to a different directory and the import fails with ModuleNotFoundError: No module named 'helper'.
You can ask Python where it found a module without importing it by using importlib.util.find_spec.
import importlib.util
spec = importlib.util.find_spec("json")
print(spec.origin)
print(spec.submodule_search_locations)For a plain module, origin is the file path. For a package, submodule_search_locations lists the directories that hold its submodules. If nothing is found, find_spec returns None.
Ways to extend the path
There are four common ways to add a directory to the search.
Install the package
The recommended approach is to install your code with pip. Installed packages land in site-packages, which is already on sys.path. A later chapter covers project layout and installing your own package. During development, pip install -e . creates an editable install that points back at your source tree.
Set PYTHONPATH
PYTHONPATH is a list of directories separated by : on Linux and macOS, or ; on Windows. Python inserts them after the script directory and before the standard library.
PYTHONPATH=/home/me/libs python main.pyThis is handy for quick experiments. It is a poor fit for shared projects, because every user and every tool must set it correctly.
Modify sys.path at runtime
You can change the list directly before the import happens.
import sys
from pathlib import Path
libs = Path(__file__).resolve().parent / "libs"
sys.path.append(str(libs))
import vendored_toolUse append to search the directory last, or insert(0, ...) to search it first. Inserting at the front is risky, because the new directory can shadow standard library modules. Keep in mind that this edit affects the whole process, and only imports that run after the edit see it.
Use a .pth file
A text file with the extension .pth placed in site-packages adds each listed directory to sys.path at startup. Each line is a path. Lines that begin with import are executed as code. Editable installs often use this mechanism.
How one directory is searched
For each directory on sys.path, Python asks whether it contains the requested name. For the name tools, it looks for these candidates in a fixed order:
- A directory named
toolsthat contains__init__.py, which is a regular package. - A file such as
tools.py, or a compiled extension module liketools.cpython-312-x86_64-linux-gnu.so. - A directory named
toolswith no__init__.py. Python remembers this as a possible namespace package portion and keeps searching later entries.
A regular package or module found at any entry wins over a bare directory found earlier. A later chapter covers namespace packages in detail.
For dotted names such as shapes.util.mathx, Python imports shapes through sys.path, then searches for util only inside shapes.__path__, and so on. The __path__ attribute of a package is its own small search path for submodules.
Bytecode caching
When Python loads a .py file, it saves compiled bytecode in a __pycache__ directory as a .pyc file. On the next import it reuses the bytecode if the source file's modification time and size still match. This speeds up loading but does not change which module is found.
Common errors and how to read them
ModuleNotFoundError
The message No module named 'x' means no sys.path entry produced x. Check these causes in turn:
- The package is not installed in the environment that runs your script. Check with
python -m pip show x, using the same interpreter. - You have several Python installations, and
pipbelongs to a different one thanpython. Always usepython -m pip. - The file is in a directory that is not on
sys.path, usually because you launched the script from a different place than you expected. - A typo in the name, or the wrong case on a case-sensitive file system.
For the dotted case, No module named 'shapes.util'; 'shapes' is not a package means Python found a plain module called shapes instead of a directory.
Shadowing
Shadowing happens when your file has the same name as another module, and yours appears earlier in sys.path. A common example is a script named email.py or test.py. Another module that does import email now receives your file. The symptoms are strange AttributeError messages, such as module 'random' has no attribute 'randint'.
To check which file was loaded, print module.__file__. To find a conflict before importing, use find_spec. Rename your file and delete any stale __pycache__ directory to fix it.
Works in the editor, fails in the terminal
An editor or test runner often adds the project root to sys.path for you. A plain python command does not. If an import works in one tool and fails in another, print sys.path[0] in both and compare.
Inspecting a failing import
This short script reports where a name would be found and what the path looks like.
import importlib.util
import sys
def where_is(name):
try:
spec = importlib.util.find_spec(name)
except ModuleNotFoundError:
spec = None
if spec is None:
print(f"{name}: not found")
for entry in sys.path:
print(" searched:", repr(entry))
else:
print(f"{name}: {spec.origin}")
where_is("json")
where_is("no_such_module_xyz")The try block matters for dotted names. find_spec("a.b") imports a first, and raises ModuleNotFoundError if a is missing.
Exercise
You run python src/tools/run.py from your home directory. The file src/tools/run.py contains import util, and util.py sits in your home directory next to the src folder. Does the import succeed? What would change if you ran python -m tools.run from inside src, assuming src/tools/__init__.py exists?
Show answer
The import fails with ModuleNotFoundError. With python script.py, the first sys.path entry is the script's directory (src/tools), not the current working directory (your home directory), and util.py is not in src/tools. Running python -m tools.run from src puts src first on the path instead. Then tools is found, but import util still fails unless util.py is in src or another sys.path entry.
Exercise
Your project has a file called json.py in the same directory as app.py. Running python app.py now fails inside a library with AttributeError: module 'json' has no attribute 'loads'. Explain why, and give two ways to confirm and fix it.
Show answer
The script directory is sys.path[0], so import json finds your json.py before the standard library one. Confirm by printing json.__file__ or running importlib.util.find_spec("json").origin. Fix it by renaming your file (and removing the stale __pycache__/json*.pyc), or by running Python with -P (3.11+) so the script directory is not added to the path.