Section 1.7: Modules, Packages, and Environments
Code that lives in one file stops being usable once there is enough of it. Splitting it across files and importing between them is the first half of this section. The second half is the one that decides whether your work runs anywhere but your own machine: a virtual environment, which is an isolated interpreter and its own installed packages, plus a written record of the exact package versions your project depends on. Without that record, "it works on my machine" is a literal and complete description of your project's reach.
Section 6 made your code survive bad input. What it did not address is the code surviving as something other than a single script. A resilient loader that only exists as three hundred lines in one file cannot be reused without dragging its whole script along, and a project that installs its dependencies into whatever interpreter happened to be first on PATH is one system update away from not running at all. Module 0 showed you PATH decides which program runs. This section is where ignoring that fact starts costing you.
Lessons
- Modules and Imports - splitting code across files and bringing names in from another one.
- The Standard Library, the Main Guard, and Entry Points - what ships with Python, and making a file usable both as a script and as an import.
- Packages, pip, and Virtual Environments - installing third-party code into an isolated, reproducible environment.
By the end you will be able to:
- Split a working script into modules and import between them without circular imports.
- Explain what the main guard does and why an imported module needs it.
- Create a virtual environment, install into it, and prove which interpreter is active.
- Produce a pinned requirements record and rebuild the environment from it on a clean machine.