liveBook · Manning

Sys.path

As explained in Python Workout: 50 ten-minute exercises

sys.path is the Python list of directory path strings searched by the import system for modules and packages.

When Python evaluates an import such as `import mymod`, it searches the directories listed in `sys.path`. The list contains directory-name strings, and Python checks them in order until it finds a matching module file. section 8.0 section 8.5

The search behavior has two practical consequences:

  • Python loads the first matching module and ignores later matches with the same name, so duplicate module names can create conflicts. section 8.0
  • You can modify the search locations through `PYTHONPATH` or `.pth` files in the installation's `site-packages` directory. section 8.5
  • `sys.path` controls where Python looks; `sys.modules` separately records modules that have already been loaded. section 8.5

Tracing a module import

With `import mymod`, Python looks for `mymod.py` in the directories named by `sys.path`. After finding the first match, it loads that file and stops searching. If another directory also contains `mymod.py`, that second file is not selected. section 8.5 section 8.0

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Defines ordered directory lookup and configuration points, stopping short of detailed import-finder internals.
Examples
Uses `import mymod` to demonstrate first-match loading and duplicate-name conflicts.
What it assumes
Assumes familiarity with import and modules while clarifying how Python finds their files.
What you can do after
Diagnose module-resolution conflicts by reasoning from sys.path order and distinguishing lookup from cached loading.
How it connects
Connects module imports with packages, PYTHONPATH, site-packages, and the sys.modules module cache.

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 Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.