AlgoMaster Logo

Standard Library

Medium Priority24 min readUpdated June 6, 2026
Listen to this chapter
Unlock Audio

Python ships with a large standard library. Hundreds of modules are already installed on your machine the moment you install Python, and most of them are battle-tested by decades of use. Knowing what's in there saves you from reinventing common pieces and from pulling in third-party packages for problems the standard library already solves. This lesson is a guided tour of the modules you'll reach for most often, grouped by what they do, with a short E-Commerce snippet for each.

We won't cover every method on every module. For each module, this lesson shows one representative snippet. The goal is breadth: by the end of the tour you should know which module to reach for, even if you still need to skim the docs for the exact API.

A Map of the Tour

The standard library is organized loosely by purpose, but the categories below are the ones a typical application developer touches most often. Everything in this chapter falls into one of these buckets.

The diagram is the table of contents. Each H2 below maps to one orange bucket. Inside each bucket, each H3 covers one module with a short snippet and a one-liner on when to use it.

Modules for Files & Paths

Anything that touches the file system lives here: reading order receipts off disk, copying product images, building paths in a platform-safe way, or creating a temporary scratch directory while you process an upload.

os and os.path

os is the low-level interface to the operating system: environment variables, process IDs, directory listings, and historically, path manipulation through os.path. For new code, pathlib is the preferred path API, but you'll still see os in older codebases and you'll still need it for things like environment variables and directory walks.

Reach for os when you need environment variables, process info, or you're working in a codebase that already uses it. For new path code, prefer pathlib.

pathlib

pathlib is the modern, object-oriented way to work with file paths. A Path object knows how to join itself with another path, check if it exists, read its text, and walk its children. Here's a taste.

Reach for pathlib whenever you'd otherwise use os.path.join, os.path.exists, or open. It reads more like English and works the same way on Windows, macOS, and Linux.

shutil

shutil (shell utilities) is the high-level file operations module. Think of it as the Python version of cp, mv, and rm -rf. Where os gives you single-file primitives, shutil gives you whole-directory operations.

Reach for shutil when you need to copy a directory tree, move a file across drives, remove a directory recursively, or get disk usage info.

tempfile

tempfile creates temporary files and directories that the OS will clean up. Useful when you need a scratch workspace, for example to unpack an uploaded archive of product images before validating them.

Reach for tempfile whenever you need a "scratch" file or directory that you don't want to clean up by hand.

Modules for Data Formats

Storing and exchanging data is one of the most common things real programs do. The standard library covers the two formats you'll meet over and over: JSON for general structured data, and CSV for tabular exports.

json

json reads and writes JSON, the format every web API speaks. json.dumps turns Python objects into a JSON string; json.loads parses a JSON string back into Python. The file-based variants (json.dump and json.load) read and write directly from open file objects.

Reach for json any time you're saving or loading data that other systems will read, especially web APIs and config files.

csv

csv reads and writes comma-separated value files. It handles the small but real complications: quoting strings that contain commas, escaping quotes, picking a different delimiter for tab-separated files. Use it instead of splitting lines on commas by hand.

Note how the third product's name has a comma in it. csv quotes the field automatically so the file is still valid CSV.

Reach for csv whenever you export to or import from spreadsheets, bulk-loading tools, or anything that speaks "rows and columns".

Modules for Dates & Time

Order timestamps, delivery dates, "added 3 days ago" displays, scheduled drops. Anything time-related goes through these two modules.

datetime

datetime is the high-level module: dates, times, and arithmetic between them.

Reach for datetime whenever you need calendar dates, wall-clock times, or arithmetic on them ("3 days from now", "due in 48 hours").

time

time is the low-level module. Its most useful pieces are time.sleep for pausing, time.time for a Unix timestamp, and time.perf_counter for high-resolution timing.

Reach for time when you need a Unix timestamp, a quick pause, or a high-precision stopwatch.

Modules for Collections & Functional Tools

These are the modules that make Python feel "batteries included". They give you specialized containers and iteration helpers that you'd otherwise reinvent every time you wrote a real program.

collections

collections adds containers that go beyond the built-in list, dict, tuple, and set. The four you'll use most often:

  • Counter for counting things.
  • defaultdict for dicts that auto-create missing values.
  • deque for fast appends and pops at both ends.
  • namedtuple for lightweight records with named fields.

Here's one snippet that exercises four of them at once.

Reach for collections whenever you find yourself counting, grouping, or building "the last N things" by hand. The right container makes the code shorter and faster.

itertools

itertools is a collection of building blocks for iteration. Three of the most useful: chain (concatenate iterables lazily), groupby (group adjacent equal items), and accumulate (running totals).

Reach for itertools whenever you need to combine, group, slice, or repeat sequences without writing the loop yourself.

functools

functools is the functional-programming toolkit. The two pieces you'll use most: lru_cache for memoizing expensive function calls, and partial for pre-filling some arguments of a function.

Reach for lru_cache when a pure function is being called repeatedly with the same arguments and the computation isn't trivially cheap.

Modules for Math & Random

Pricing math, ratings, sampling, simulated traffic, random discount codes. Everything numeric lives here.

math

math is the standard math functions: sqrt, floor, ceil, log, trig, constants like pi. It operates on regular floats, not on lists.

Reach for math whenever you need real math functions on numbers: roots, logs, trig, or precise rounding behavior.

random

random generates pseudo-random numbers and makes random choices. Useful for everything from picking a daily featured product to generating a placeholder coupon code in dev. For anything security-sensitive (passwords, tokens), use secrets instead.

Reach for random when you need shuffled lists, random samples, or quick simulations.

statistics

statistics does the obvious stats functions on lists of numbers: mean, median, mode, standard deviation. Smaller and more readable than reaching for NumPy when you only need the basics.

Reach for statistics when you need basic descriptive statistics and don't want to add NumPy as a dependency.

Modules for Text & Regex

Validating coupon codes, formatting product descriptions for the cart preview, normalizing customer names. These are the text-processing modules.

re

re is the regular expressions module. Use it for pattern matching, validation, and substitution that would be painful with plain string methods.

Reach for re when string methods like startswith, endswith, split, and find aren't expressive enough.

string

string is the boring-but-useful module of string constants and helpers: predefined character sets and a templating class. The constants come up often when validating input.

Reach for string when you need a ready-made set like "all ASCII letters" or "all digits" instead of typing them out.

textwrap

textwrap wraps and fills long text to a given width. Handy when you're printing a product description into a fixed-width cart preview or terminal output.

Reach for textwrap whenever you have long text that needs to fit into a fixed column width, like email previews or terminal tables.

Modules for System & Process

These modules talk to the running Python process itself and to other processes you spawn from it. Useful for command-line tools, scripts, and anything that has to log or shell out.

sys

sys exposes interpreter-level info: command-line arguments, standard streams, exit codes, Python version, the module search path. The pieces you'll use most are sys.argv, sys.exit, and sys.stdout / sys.stderr.

Reach for sys for low-level command-line scripts, controlled exit codes, or writing to stderr.

subprocess

subprocess runs other programs and captures their output. The standard way to shell out from Python: replace os.system, os.popen, and friends with this.

Reach for subprocess whenever you'd otherwise write os.system("..."). It's safer (no shell injection by default), more flexible, and gives you the output as a Python string.

argparse

argparse builds proper command-line interfaces: positional arguments, optional flags, help text, type conversion.

Reach for argparse whenever your script has more than one or two arguments or you want --help text for free.

logging

logging is the structured alternative to print for anything you want to keep around: timestamps, levels (DEBUG, INFO, WARNING, ERROR), routing to files.

Reach for logging once your script is more than a one-off. It scales to multi-module applications, can be turned off without code changes, and writes to files or external systems without you rewriting the calls.

Modules for Networking

Fetching data from a URL, calling a web API, building a small HTTP client. These modules let you do basic networking without a third-party library.

urllib

urllib is the standard library's HTTP client. It's lower-level than the popular third-party requests library, but it ships with Python and works for simple GET/POST calls.

Reach for urllib when you need a quick HTTP call and don't want to add a dependency. For real applications, requests is friendlier.

http.client

http.client is even lower-level than urllib: a raw HTTP/1.1 client. You'll rarely write code against it directly, but it's good to know it exists for cases where you need precise control over headers, connection reuse, or streaming. For most everyday HTTP work, urllib or the third-party requests library is the better choice.

Other Useful Modules

A handful of modules don't fit neatly into the buckets above but show up often enough that they belong in any tour.

uuid

uuid generates universally unique identifiers. Useful for order IDs, idempotent keys, or any ID you want to be globally unique without a database round-trip.

Reach for uuid.uuid4() whenever you need a unique identifier you can hand to clients or store in a database without coordinating with a server.

hashlib

hashlib provides standard cryptographic hash functions: SHA-256, SHA-512, MD5, and others. Use it for fingerprinting files, building cache keys, or verifying that two payloads match.

A common temptation is to use hashlib to hash passwords. Don't. Plain SHA-256 is too fast to be safe for passwords. Use a proper password-hashing function from a dedicated library (bcrypt, argon2, or the standard library's hashlib.scrypt with deliberate parameters). For non-password fingerprinting and integrity checks, hashlib is perfect.

secrets

secrets is the cryptographically-secure cousin of random. Use it whenever the value is going somewhere security-sensitive: password reset tokens, API keys, session IDs.

Reach for secrets instead of random any time the output influences security. random is fine for game logic and simulations; secrets is the only safe choice for tokens, codes, and IDs an attacker might guess.

pickle

pickle serializes any Python object to bytes and deserializes it back. Powerful, because it can round-trip almost anything: classes, nested structures, even functions. Dangerous, because loading a pickle file is equivalent to running the code that produced it.

Reach for pickle only when you control both ends of the pipe and need to save something json can't represent.

dataclasses

dataclasses (added in Python 3.7) turns a class into a typed record with auto-generated __init__, __repr__, and equality methods. One line at the top, and you get a clean container type.

Reach for dataclasses when you'd otherwise write a small class with three attributes and a constructor that just assigns them.

enum

enum defines a fixed set of named constants: order statuses, user roles, payment methods. Cleaner than scattered string literals like "placed" and "shipped", and the IDE can catch typos.

Reach for enum whenever you have a small, closed set of values and you'd otherwise type the same strings in many places.

Quiz

Standard Library Quiz

10 quizzes