Sub topic 2
How Python Finds Modules: `sys.path`
Assume you know basic Python syntax, can run scripts from a terminal, and understand files and directories. Python uses sys.path to decide where to search when an import is requested.
The module search path
A module is a Python file that Python loads as a module object. The file's location is only one part of the process. Python searches locations in sys.path, a list of directories and other import locations.
Typical entries include:
- The script's directory
- The current environment's library directory
- Installed package directories
- Entries added through
PYTHONPATH
Python checks these locations in order. The first matching module wins.
import sys
print("Python searches these locations:")
for location in sys.path:
print(location)A file named json.py in your project can shadow the standard-library json module if its directory appears first. Avoid naming files after standard-library or third-party packages.
Packages and submodules
A package is a directory that groups related modules. A regular package contains an __init__.py file:
shapes/
__init__.py
circle.py
square.pyThe package name is shapes. Its files are submodules, so circle.py becomes shapes.circle.
__init__.py runs when the package is imported. It can define package setup or expose selected names.
Absolute and relative imports
An absolute import starts at a top-level package or module:
from shapes.circle import areaA relative import starts from the current package. One dot means the current package:
# Inside shapes/report.py
from .circle import area
from .utils.formatting import format_areaRelative imports keep internal package relationships clear, but they require the file to be imported as part of a package. Running python shapes/report.py directly can therefore fail. Run the module from the project root instead:
python -m shapes.reportExercise
If both /project and /project/vendor appear in sys.path, and both contain tools.py, which file does import tools load?
Show answer
Python loads the first matching tools.py, so the order of sys.path determines the result.