Programming Search⌘K

Featureintro

The standard library tour

Also called standard library tour, batteries included, Python stdlib, brief tour of the standard library, tutorial chapter 10, tutorial chapter 11.

Python ships with a large standard library, the "batteries included" idea. The two tour chapters of the tutorial show common modules: os, re, math, datetime, zlib, doctest and logging.

Language
Python

Synopsis

import math
import re
import statistics
import zlib

print(re.findall(r"\bf[a-z]*", "which foot or hand fell fastest"))
print(math.log(1024, 2))
print(statistics.median([2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]))
s = b"witch which has which witches wrist watch"
print(zlib.decompress(zlib.compress(s)) == s, zlib.crc32(s))
Output
['foot', 'fell', 'fastest']
10.0
1.25
True 226805979

Semantics

r1. "Python’s standard library is extensive, offering a wide range of facilities".1 It "contains built-in modules (written in C) that provide access to system functionality such as file I/O", "as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming."1

r2. "Python has a “batteries included” philosophy. This is best seen through the sophisticated and robust capabilities of its larger packages."2 A program imports a standard module with import, with no install step. Example: tour.

r3. The first tour covers the operating system, file wildcards, command-line arguments, error output, string pattern matching, mathematics, internet access, dates and times, data compression, performance measurement and quality control.2 Example: argparse.

r4. "This second tour covers more advanced modules that support professional programming needs. These modules rarely occur in small scripts."3 It covers output formatting, templating, binary record layouts, threads, logging, weak references, list tools and decimal arithmetic.3 Example: struct.

r5. "In addition to the standard library, there is an active collection of hundreds of thousands of components" on the Python Package Index.1

Examples

import argparse

parser = argparse.ArgumentParser(prog="top", description="Show top lines from each file")
parser.add_argument("filenames", nargs="+")
parser.add_argument("-l", "--lines", type=int, default=10)
args = parser.parse_args(["--lines=5", "alpha.txt", "beta.txt"])
print(args.lines, args.filenames)
Output
5 ['alpha.txt', 'beta.txt']

"The argparse module provides a more sophisticated mechanism to process command-line arguments."2 Here the list replaces sys.argv, so the example runs with no real arguments.

import datetime as dt

day = dt.date(2003, 12, 2)
print(day.strftime("%d %b %Y is a %A"))
print((day - dt.date(1964, 7, 31)).days)
Output
02 Dec 2003 is a Tuesday
14368

"The datetime module supplies classes for manipulating dates and times in both simple and complex ways."2 Subtraction of two dates gives a timedelta.

import doctest

def average(values):
    """Computes the arithmetic mean of a list of numbers.

    >>> print(average([20, 30, 70]))
    40.0
    """
    return sum(values) / len(values)

print(doctest.testmod())
Output
TestResults(failed=0, attempted=1)

"The doctest module provides a tool for scanning a module and validating tests embedded in a program’s docstrings."2

import struct

record = struct.pack("<HI", 7, 1024)
print(len(record), record.hex())
print(struct.unpack("<HI", record))
Output
6 070000040000
(7, 1024)

"The struct module provides pack() and unpack() functions for working with variable length binary record formats."3 < means little-endian with standard sizes, H is two bytes and I is four bytes.3

Pitfalls

This code raises TypeError, on purpose.

from os import *

with open("notes.txt") as f:
    print(f.read())

The tour says: "Be sure to use the import os style instead of from os import *. This will keep os.open() from shadowing the built-in open() function which operates much differently."2 Here open is os.open, which needs a flags argument.

Comparison

Each tour section has its own page in this guide, for example Operating System Interface, File Wildcards, String Pattern Matching, Mathematics, Data compression, Output Formatting, Templating, Multi-threading, Tools for working with lists and Decimal floating-point arithmetic. See Standard library map for all the chapters of the library reference.

References

  1. The Python standard library, Python 3.15 documentation, Introduction paragraphs
  2. 10. Brief tour of the standard library, Python 3.15 documentation, 10.1 to 10.12
  3. 11. Brief tour of the standard library, part II, Python 3.15 documentation, 11.1 to 11.8

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source