Chapter 6
The Standard Library Exists
Choose an API for the Job
Installing a package is sometimes the right answer. It is not the first answer to every problem, because a great deal already comes with Python.
A .py files, while some are packages with several files. You have already used the idea: import requests reached for installed code. The difference here is that the three modules in this chapter arrive with Python itself. Together they are part of the standard library, and these three need no pip install.
One word before we start, because it gets used for two different things and the collision causes real confusion. In this chapter, a module’s API means its public surface: the
This chapter builds one activity briefing. It has three jobs:
measure the distance between two calendar dates;
count activities by category;
describe the center of a set of session lengths.
That short job
Go from the job to one contract
Use the Python library index as a map, not as a book to read from page one. For each job:
Write the job in ordinary words: “parse an ISO date and subtract dates.”
Find the likely module:
datetime.Find the
or function that owns the operation: date.fromisoformat.Read its signature,
, accepted input, and documented failures. Try one tiny example before adding it to the project.
The same route points “count labels” toward collections.Counter, and “find the mean and median” toward statistics. We will use only those three modules. The standard library is large; this chapter is not a tour of it.
Importing is not installing
These two lines both import a module:
import statistics
import requests
But only statistics is distributed with Python. The earlier environment chapter installed requests from a package pip install statistics, you have skipped the first question: whether Python already supplies the capability.
The documentation URL is another clue. The reference for these modules lives under docs.python.org/3/library/. A third-party project owns its own release and installation story.
You need to calculate the median of some numbers. What is the best first move?
A documentation page shows the signature, return value, accepted input, and exceptions for a function. What can you decide from that information?
Next, you will use this route on a real date calculation and start the chapter’s single project file.
Stuck on which module owns a job? Describe the job to Monty in ordinary words and ask which part of the standard library covers it. Ask for the documentation page rather than the code, so you practice reading the contract yourself.