liveBook · Manning

Sys.path

As explained in The Quick Python Book, Fourth Edition

A module search path is the ordered set of directories that a language runtime searches to locate importable modules and packages.

sys.path is an ordered list of directories Python searches when an import statement requests a module. Python uses the first matching module and raises ImportError when none matches. section 10.4

Python initializes sys.path from PYTHONPATH or installation defaults. A script adds its containing directory first; an interactive session uses an empty first element to represent the current directory. section 10.4

Make application modules discoverable by:

  • Keeping modules beside the program that uses them. section 10.4.1
  • Adding a shared site-specific directory to sys.path in code. section 10.4.1
  • Setting PYTHONPATH or adding directories through a .pth file. section 10.4.1
  • Installing third-party modules into a directory already included in the search path. section 10.6

Inspecting the search path

import sys sys.path The resulting list varies by installation, but its order determines which matching module Python imports first. section 10.4

import sys
sys.path
 
 
import sys
sys.path
['/content',
 '/env/python',
 '/usr/lib/python310.zip',
 '/usr/lib/python3.10',
 '/usr/lib/python3.10/lib-dynload',
 '',
 '/usr/local/lib/python3.10/dist-packages',
 '/usr/lib/python3/dist-packages',
 '/usr/local/lib/python3.10/dist-packages/IPython/extensions',
 '/root/.ipython']                                        #1
#1 This listing will depend on your Python setup.

Inspect a concrete sys.path listing and observe how Python records installation directories, the current directory, and extension locations. section 10.4

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains ordered lookup, initialization sources, execution-context differences, and practical configuration options.
Examples
Uses sys.path inspection, a local mymath.py module, shared module directories, and a mymodules.pth file.
What it assumes
Assumes familiarity with Python modules and import statements while establishing how the runtime locates them.
What you can do after
Operate/configure Python's module discovery by inspecting sys.path and selecting directory, PYTHONPATH, or .pth placement.
How it connects
Connects import statements, modules, packages, PYTHONPATH, .pth files, and ImportError.

Also explained in

Compare how 3 books explain sys.path →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.