Chapter Nine · Beyond One File

Modules, the Standard Library and Environments

Real programs grow past one file, and real work leans on code other people wrote. This chapter shows how to split a program across files, what ships with Python already, how to work with dates, how to give each project its own private set of packages, and how to install a package safely.

Since Chapter 2 you have been writing one line that this chapter finally explains: from decimal import Decimal. It borrows a tool from somewhere else. That somewhere is a module, and modules are how Python programs grow beyond one file and how they use the enormous amount of code that other people have already written and tested.

Five topics. Splitting your own program into several files, and the one line that lets a file be both run and imported. The standard library, the modules that come with Python, with a short tour of the ones used most. Dates and times, which look simple until you do arithmetic with them. Virtual environments, which give each project its own private shelf of packages. And pip, which fetches packages from the public index, together with the care that fetching code from strangers deserves.

Where every name you import comes from
Your own modules
the .py files in your project, such as tips.py
Packages from PyPI
installed per project with pip, such as requests
The standard library
ships with Python: csv, json, decimal, datetime, pathlib
The language itself
print, len, int, list: always available, no import

Topics in This Chapter