liveBook · Manning

Sys.path

As explained in Python Workout, Second Edition

sys.path is the list of directory names that Python searches when locating importable modules and packages.

sys.path is a list of directory names that Python searches when locating an importable module or package. Python checks the directories in order and stops at the first matching file. section 9.1

Inspecting the import search path

Use sys.path to see the directories Python will search: `import sys` followed by `print(sys.path)`. If two directories contain modules with the same name, the module in the first matching directory wins; later matches are ignored. section 9.1

Keep these import behaviors in mind when diagnosing missing modules or unexpected definitions:

  • Import the module name, not its filename: use `import os`, rather than `import os.py`. section 9.1
  • Place a package directory somewhere on sys.path before importing modules such as `mypackage.first`. section 9.9
  • Change the search path through PYTHONPATH or `.pth` files in the installation’s site-packages directory. section 9.5
  • Separate search from loading: Python consults sys.modules to avoid loading an already loaded module again. section 9.5

How Python Workout, Second Edition covers it

How deep it goes
Explains ordered lookup, duplicate-name conflicts, configuration methods, and its boundary with sys.modules.
Examples
Uses os, mymod.py, duplicate module directories, and a mypackage directory containing first.py.
What it assumes
Assumes familiarity with import and modules while distinguishing packages and module caching.
What you can do after
Diagnose import conflicts and configure module discovery through sys.path, PYTHONPATH, or .pth files.
How it connects
Connects import, modules, packages, PYTHONPATH, .pth files, and sys.modules.

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, Second Edition. The section links point to the parts of the book it draws on.