Part 07 / Topic 6 of 9
How Python finds modules (sys.path)
When you write import x, Python searches a list of folders called sys.path, in order:
- The folder of the script you ran
- Folders in the
PYTHONPATHenvironment variable (if set) - The standard library folders
site-packages(the folder where pip installs packages)
The first match wins. If nothing matches you get ModuleNotFoundError.
Real-world example: check why an import fails.
import sys
for folder in sys.path[:3]:
print(folder)
# e.g.
# /home/you/projects/shop <- folder of your script
# /usr/lib/python313.zip
# /usr/lib/python3.13
๐ Going deeper: in the interactive prompt (REPL) or with
python -m, the first entry is the current folder instead of the script's folder. Avoid "fixing" imports withsys.path.append(...); fix the folder layout or install your code into the venv instead.
Done here? The practice set for Part 7 โ 7 exercises with solutions โ is on the part page.