Standard library quick reference
The standard library ships with every Python 3.12+ install, so nothing here needs pip. This page maps each common job to its module. It gives runnable examples for the areas that no other page covers, and links to the main page for the rest. Use it for scripts, automation, web back ends and data work alike.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| count things | collections.Counter |
Counter(words).most_common(3) |
| group values under a key | collections.defaultdict(list) |
groups[key].append(row) |
| a fast queue or a rolling window | collections.deque(maxlen=n) |
window.append(x); q.popleft() |
| a small record class | @dataclasses.dataclass |
@dataclass(frozen=True, slots=True) |
| a fixed set of named constants | enum.Enum, enum.StrEnum |
class Status(StrEnum): OK = auto() |
| cut a stream into chunks | itertools.batched(it, n) |
for chunk in batched(ids, 500): |
| loop over a grid of options | itertools.product |
product(lrs, depths) |
| cache a slow pure function | functools.cache / lru_cache |
@cache above the def |
| fix some arguments of a function | functools.partial |
partial(round, ndigits=2) |
| top k items without a full sort | heapq.nlargest(k, xs, key=...) |
nlargest(3, orders, key=itemgetter(1)) |
| insert into a sorted list | bisect.insort / bisect_left |
bisect_left(prices, 100) |
| parse or format a date | datetime.date.fromisoformat, strftime |
f"{d:%Y-%m-%d}" |
| the current time, safely | datetime.now(UTC) |
from datetime import UTC |
| convert between time zones | zoneinfo.ZoneInfo |
dt.astimezone(ZoneInfo("Europe/Berlin")) |
| find or replace a text pattern | re |
re.findall(r"\d+ms", line) (see regex) |
| exact decimal money | decimal.Decimal |
Decimal("19.99") * 3 |
| summary statistics of a list | statistics |
median(xs), quantiles(xs, n=4) |
| reproducible random numbers | random.Random(42) |
rng.sample(ids, 5) |
| build and inspect paths | pathlib.Path |
Path("data") / "sales.csv" |
| list files by pattern | Path.glob, Path.rglob |
sorted(Path("data").glob("*.csv")) |
| copy, move or zip files | shutil |
shutil.copytree(src, dst, dirs_exist_ok=True) |
| a temporary file or folder | tempfile.TemporaryDirectory() |
with TemporaryDirectory() as tmp: |
| read an environment variable | os.environ.get |
os.environ.get("LOG_LEVEL", "INFO") |
| run another program | subprocess.run([...], check=True) |
run(["git", "status"], capture_output=True) |
| read or write JSON | json.load, json.dumps |
json.dumps(obj, indent=2) |
| read CSV rows as dicts | csv.DictReader |
for row in csv.DictReader(f): |
| read a TOML config | tomllib.load (binary file) |
with open("pyproject.toml", "rb") as f: tomllib.load(f) |
| a command-line interface | argparse.ArgumentParser |
parser.add_argument("--top", type=int) |
| log messages with levels | logging.getLogger(__name__) |
log.warning("rows dropped: %d", n) |
| run work in parallel | concurrent.futures |
ThreadPoolExecutor().map(fetch, urls) |
| a local SQL database | sqlite3 |
sqlite3.connect("data/shop.db") |
| split or build a URL | urllib.parse |
urlsplit(url).query, urlencode(params) |
| an HTTP status name | http.HTTPStatus |
HTTPStatus(404).phrase |
| wrap or shorten text | textwrap |
textwrap.shorten(text, 40) |
| a unique id | uuid.uuid4() |
str(uuid.uuid4()) |
| a file checksum | hashlib.sha256 |
hashlib.file_digest(f, "sha256") |
| a secure token or password | secrets |
secrets.token_urlsafe(16) |
| time a block of code | time.perf_counter() |
start = perf_counter() |
| benchmark a small snippet | timeit.timeit |
timeit(lambda: sum(xs), number=100) |
| copy nested data | copy.deepcopy |
cfg2 = copy.deepcopy(cfg) |
Module map
Section titled “Module map”| Module | What for | Key functions and classes |
|---|---|---|
collections |
specialized containers | Counter, defaultdict, deque, namedtuple, ChainMap, OrderedDict |
itertools |
lazy iteration building blocks | chain, islice, batched, groupby, accumulate, pairwise, product, combinations |
functools |
higher-order functions | cache, lru_cache, partial, reduce, wraps, cached_property, singledispatch |
operator |
operators as functions | itemgetter, attrgetter, methodcaller, add, mul |
heapq |
priority queues | heappush, heappop, nlargest, nsmallest, merge |
bisect |
binary search in sorted lists | bisect_left, bisect_right, insort |
copy |
copies of objects | copy (shallow), deepcopy, replace (3.13+) |
dataclasses |
record classes without boilerplate | dataclass, field, asdict, astuple, replace, fields |
enum |
named constants | Enum, StrEnum, IntEnum, Flag, auto |
typing |
type hints | TypedDict, Protocol, Literal, Self, cast (see type hints) |
contextlib |
with helpers |
contextmanager, suppress, closing, ExitStack, chdir |
datetime |
dates, times, durations | date, datetime, timedelta, UTC, fromisoformat, strptime |
zoneinfo |
IANA time zones | ZoneInfo("America/Chicago") |
time |
clocks and sleeping | perf_counter, monotonic, time, sleep |
timeit |
micro-benchmarks | timeit, repeat, python -m timeit |
re |
regular expressions | search, fullmatch, findall, finditer, sub, split, compile |
string |
character sets and templates | ascii_letters, digits, punctuation, Template |
textwrap |
wrapping and indenting text | wrap, fill, shorten, dedent, indent |
difflib |
text differences and fuzzy matches | get_close_matches, unified_diff, SequenceMatcher |
unicodedata |
Unicode normalization | normalize("NFKC", s), name, category |
math |
float math | sqrt, log, isclose, fsum, prod, comb, inf, nan |
statistics |
descriptive statistics | mean, median, stdev, quantiles, correlation, NormalDist |
random |
pseudo-random numbers | Random(seed), choice, choices, sample, shuffle, gauss |
decimal, fractions |
exact arithmetic | Decimal("0.10"), quantize, Fraction(1, 3) |
os |
the operating system | environ, getenv, cpu_count, scandir, getpid |
sys |
the interpreter | argv, exit, executable, path, version_info, stdin, stderr |
pathlib |
paths as objects | Path, /, glob, rglob, read_text, mkdir, stem, suffix |
shutil |
high-level file operations | copy2, copytree, move, rmtree, make_archive, which |
tempfile |
temporary files and folders | TemporaryDirectory, NamedTemporaryFile, mkdtemp |
glob, fnmatch |
shell-style patterns | glob("**/*.py", recursive=True), fnmatch(name, "*.csv") |
subprocess |
run other programs | run, CalledProcessError, TimeoutExpired |
json |
JSON text | load, loads, dump, dumps(indent=2, default=str) |
csv |
CSV files | reader, writer, DictReader, DictWriter |
tomllib |
read TOML (read only) | load(binary_file), loads(text) |
pickle |
Python object files (trusted data only) | dump, load |
zipfile, gzip, tarfile |
archives and compression | ZipFile, gzip.open, tarfile.open |
argparse |
command-line interfaces | ArgumentParser, add_argument, add_subparsers, parse_args |
logging |
leveled log messages | getLogger, basicConfig, Handler, Formatter, exception |
warnings |
soft deprecations | warn, catch_warnings, simplefilter |
traceback |
format errors | print_exc, format_exception |
concurrent.futures |
thread and process pools | ThreadPoolExecutor, ProcessPoolExecutor, as_completed |
threading, multiprocessing |
low-level concurrency | Thread, Lock, Event, Process, Pool |
asyncio |
asynchronous I/O | run, gather, TaskGroup, Semaphore, timeout, to_thread |
queue |
thread-safe queues | Queue, put, get, task_done |
sqlite3 |
an embedded SQL database | connect, execute, executemany, Row, commit |
urllib.parse |
URLs | urlsplit, urljoin, urlencode, parse_qs, quote |
urllib.request |
simple HTTP requests | urlopen, Request |
http |
HTTP constants and a test server | HTTPStatus, python -m http.server |
uuid |
unique ids | uuid4, UUID, uuid7 (3.14+) |
hashlib |
checksums and hashes | sha256, md5, file_digest, hexdigest |
hmac |
signed messages | hmac.new(key, msg, "sha256"), compare_digest |
secrets |
security tokens | token_hex, token_urlsafe, choice, compare_digest |
base64 |
binary as text | b64encode, urlsafe_b64decode |
importlib.metadata |
installed package versions | version("pandas"), packages_distributions |
pprint |
readable nested output | pp, pformat |
inspect |
look at live objects | signature, getsource, isfunction, iscoroutinefunction |
configparser |
INI-style config files | ConfigParser, read, getint, getboolean |
xml.etree.ElementTree |
parse and build XML | parse, fromstring, find, findall, iter |
html |
HTML escaping | escape, unescape; html.parser.HTMLParser |
ipaddress |
IP addresses and networks | ip_address, ip_network, addr in network |
shlex |
shell-like splitting and quoting | split("a 'b c'"), quote, join |
struct |
binary records | pack, unpack, calcsize |
weakref |
references that do not keep objects alive | ref, WeakValueDictionary, finalize |
platform |
OS and machine details | system, machine, python_version |
getpass |
read a password without echo | getpass, getuser |
signal |
handle OS signals | signal(SIGTERM, handler), SIGINT |
graphlib |
dependency ordering | TopologicalSorter(graph).static_order() |
calendar |
calendars and month facts | monthrange, isleap, month_name |
email, smtplib |
build and send mail | email.message.EmailMessage, smtplib.SMTP_SSL |
Covered on other pages
Section titled “Covered on other pages”Several standard library modules have their own master cheat sheet page. This page only lists them in the module map.
| Topic | Modules | Main page |
|---|---|---|
| containers, top k, sorted lists | collections, heapq, bisect |
collections module, heapq and bisect |
| lazy iteration, chunks, combinations | itertools |
itertools |
partial, reduce, key functions |
functools, operator |
map, filter, reduce and partial, key functions |
caching, wraps, contextmanager |
functools, contextlib |
decorators and context managers |
| paths, files, folders | pathlib, shutil, tempfile |
pathlib, shutil, tempfile and walking folders |
| JSON, CSV, TOML, pickle | json, csv, tomllib, pickle |
JSON, CSV, TOML |
strftime codes |
datetime |
dates and times in f-strings |
| regular expressions | re |
regex |
| logging, tracebacks, warnings | logging, traceback, warnings, pdb |
logging |
| record classes | dataclasses, typing.NamedTuple |
data containers |
| named constants | enum |
enums |
| interfaces | abc, typing.Protocol |
ABC vs Protocol |
| type hints | typing, collections.abc |
type hints |
| thread and process pools, async | concurrent.futures, threading, asyncio, queue |
performance and concurrency |
timeit, cProfile, tracemalloc in depth |
timeit, cProfile, pstats |
measure |
Dates and times: datetime and zoneinfo
Section titled “Dates and times: datetime and zoneinfo”from datetime import UTC, date, datetime, timedeltafrom zoneinfo import ZoneInfo
d = date.fromisoformat("2024-05-01")print(d.strftime("%a %d %b %Y"), d.isocalendar().week, d + timedelta(days=30))parsed = datetime.strptime("01/05/2024 08:25", "%d/%m/%Y %H:%M") # day firstprint(parsed.isoformat())
logged = datetime(2024, 5, 1, 13, 25, tzinfo=UTC) # store aware UTC timesprint(f"{logged.astimezone(ZoneInfo('America/Chicago')):%H:%M %Z}")print((datetime(2024, 5, 2, tzinfo=UTC) - logged) // timedelta(hours=1), "hours")Wed 01 May 2024 18 2024-05-312024-05-01T08:25:0008:25 CDT10 hoursThe strftime codes are on the strings page.
Text: re, string, textwrap and difflib
Section titled “Text: re, string, textwrap and difflib”import difflibimport reimport stringimport textwrap
line = "2024-05-01 08:04:01,354 INFO [api] 10.0.3.17 GET /api/v1/reports 200 87ms"m = re.search(r"(?P<method>GET|POST) (?P<path>\S+) (?P<status>\d{3})", line)print(m["method"], m["path"], int(m["status"]))
print(string.ascii_lowercase[:5], string.digits, len(string.punctuation))print(string.Template("Hello $name").substitute(name="Ada")) # safe user templatesprint(textwrap.shorten("Cotton Bed Sheet Set, queen size, white", width=24))print(textwrap.dedent(" a\n b").splitlines())print(difflib.get_close_matches("Chicgo", ["Chicago", "Houston", "Boston"]))GET /api/v1/reports 200abcde 0123456789 32Hello AdaCotton Bed Sheet [...]['a', ' b']['Chicago']The full regex syntax and the re functions are on the regex page.
Numbers: math, statistics, random and decimal
Section titled “Numbers: math, statistics, random and decimal”import mathimport randomimport statisticsfrom decimal import ROUND_HALF_UP, Decimalfrom fractions import Fraction
print(math.isclose(0.1 + 0.2, 0.3), math.fsum([0.1] * 10), math.comb(5, 2))latencies = [87, 88, 93, 31, 42, 45, 32, 44, 1188]print(statistics.median(latencies), round(statistics.mean(latencies), 1))print(statistics.quantiles(latencies, n=4)) # quartile cut points
rng = random.Random(42) # a private, seeded generatorprint(rng.randint(1, 6), rng.choice(["S01", "S02", "S03"]), rng.sample(range(10), 3))
price = Decimal("2.675")print(price.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP), round(2.675, 2))print(Fraction(1, 3) + Fraction(1, 6))True 1.0 1045 183.3[37.0, 45.0, 90.5]6 S01 [0, 4, 3]2.68 2.671/2The OS: os, sys, shutil, tempfile and subprocess
Section titled “The OS: os, sys, shutil, tempfile and subprocess”import osimport shutilimport subprocessimport sysimport tempfilefrom pathlib import Path
print(os.environ.get("APP_MODE", "dev"), sys.version_info >= (3, 12))
with tempfile.TemporaryDirectory() as tmp: # deleted after the block out = Path(tmp) / "backup" shutil.copytree("data/reports", out) print(sorted(p.name for p in out.iterdir())[:2])
result = subprocess.run( [sys.executable, "-c", "print(6 * 7)"], # a list, never a shell string capture_output=True, text=True, check=True,)print(result.returncode, result.stdout.strip())dev True['2024-01.csv', '2024-02.csv']0 42The full pathlib reference is on the files and formats page.
Command line: argparse
Section titled “Command line: argparse”import argparse
parser = argparse.ArgumentParser(prog="report", description="Summarize a log file.")parser.add_argument("path")parser.add_argument("--level", choices=["INFO", "WARNING", "ERROR"], default="INFO")parser.add_argument("-n", "--top", type=int, default=5)parser.add_argument("--dry-run", action="store_true")args = parser.parse_args(["data/logs/app.log", "--top", "3", "--dry-run"])print(args.path, args.level, args.top, args.dry_run) # --dry-run -> dry_rundata/logs/app.log INFO 3 TrueLogging setup, levels and handlers are on the errors and debugging page.
Databases: sqlite3
Section titled “Databases: sqlite3”import sqlite3
with sqlite3.connect("file:data/shop.db?mode=ro", uri=True) as conn: # read-only conn.row_factory = sqlite3.Row # rows behave like dicts rows = conn.execute( "SELECT region, COUNT(*) AS n FROM stores WHERE size_sqm > ? GROUP BY region " "ORDER BY region", (2000,), # parameters: never format values into SQL ).fetchall()print([(r["region"], r["n"]) for r in rows])
mem = sqlite3.connect(":memory:")mem.execute("CREATE TABLE t (id TEXT PRIMARY KEY, qty INTEGER)")with mem: # commits on success, rolls back on an error mem.executemany("INSERT INTO t VALUES (?, ?)", [("a", 2), ("b", 5)])print(mem.execute("SELECT SUM(qty) FROM t").fetchone()[0])mem.close() # `with conn:` manages the transaction, not the connection[('East', 2), ('North', 1), ('South', 2), ('West', 1)]7Web basics: urllib and http
Section titled “Web basics: urllib and http”from http import HTTPStatusfrom urllib.parse import parse_qs, quote, urlencode, urljoin, urlsplit
url = "https://api.example.com/api/v1/products?page=2&category=Home"parts = urlsplit(url)print(parts.netloc, parts.path, parse_qs(parts.query))print(urlencode({"q": "bed sheet", "page": 3}), quote("a b/c", safe=""))print(urljoin("https://api.example.com/api/v1/", "products/P026"))print(HTTPStatus(429).phrase, HTTPStatus.NOT_FOUND.value, HTTPStatus(503).is_server_error)api.example.com /api/v1/products {'page': ['2'], 'category': ['Home']}q=bed+sheet&page=3 a%20b%2Fchttps://api.example.com/api/v1/products/P026Too Many Requests 404 Trueimport jsonfrom urllib.request import Request, urlopen
req = Request("https://api.example.com/api/v1/products", headers={"Accept": "application/json"})with urlopen(req, timeout=10) as resp: # raises HTTPError for 4xx and 5xx data = json.load(resp)For real API work, httpx or requests handle sessions, retries and JSON more simply: see module 16: APIs and web data.
Ids and security: uuid, hashlib and secrets
Section titled “Ids and security: uuid, hashlib and secrets”import hashlibimport secretsimport uuid
run_id = uuid.uuid4() # random; different on every runprint(len(str(run_id)), run_id.version)print(hashlib.sha256(b"sales-pipeline").hexdigest()[:16]) # same input, same hashwith open("data/stores.csv", "rb") as f: print(hashlib.file_digest(f, "sha256").hexdigest()[:16]) # file checksumtoken = secrets.token_urlsafe(16) # for reset links, API keysprint(len(token) >= 16, secrets.compare_digest("abc", "abc"))36 4d4feb518a643f2180ca4294e9a1ab317True True| Need | Use | Not |
|---|---|---|
| a password reset token, API key | secrets.token_urlsafe(32) |
random (predictable) |
| store a password | hashlib.scrypt(pw, salt=..., n=2**14, r=8, p=1) or a library such as argon2 |
a plain sha256 |
| check a file download | hashlib.file_digest(f, "sha256") |
md5 for security |
| compare secrets | secrets.compare_digest(a, b) |
== (leaks timing) |
| a database key | uuid.uuid4(); uuid.uuid7() (3.14+, time-ordered) |
id(obj) |
Timing: time and timeit
Section titled “Timing: time and timeit”import timeimport timeit
values = list(range(10_000))start = time.perf_counter() # a monotonic, high-resolution clocktotal = sum(values)elapsed = time.perf_counter() - startper_call = timeit.timeit(lambda: sum(values), number=200) / 200print(total, elapsed >= 0, per_call < 0.01) # print comparisons, not raw timings49995000 True True| Clock | Use |
|---|---|
time.perf_counter() |
durations and benchmarks |
time.monotonic() |
timeouts; never goes backward |
time.time() |
a Unix timestamp; can jump when the clock is set |
time.process_time() |
CPU time of this process only |
datetime.now(UTC) |
a timestamp to store or show |
Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
a file named random.py, json.py or logging.py |
AttributeError: module 'random' has no attribute ... |
rename your file; it shadows the module |
datetime.now() without a zone |
naive local time; differs per machine | datetime.now(UTC) |
| naive and aware datetimes mixed | TypeError: can't compare offset-naive and offset-aware datetimes |
make all of them aware in UTC |
%m/%d versus %d/%m |
1 May read as 5 January, no error | test a day above 12 |
subprocess.run("cmd " + user_input, shell=True) |
shell injection | a list of arguments, no shell |
subprocess.run without check=True |
a failing command passes silently | check=True |
with sqlite3.connect(...) as conn |
commits, but does not close the connection | conn.close() or contextlib.closing |
| SQL built with f-strings | SQL injection, quoting bugs | ? placeholders and a parameter tuple |
random for tokens |
predictable values | secrets |
random.seed(42) with the global functions |
other code shifts your sequence | rng = random.Random(42) |
@dataclass with items: list = [] |
ValueError: mutable default ... is not allowed |
field(default_factory=list) |
ZoneInfo on Windows |
ZoneInfoNotFoundError |
pip install tzdata |
secrets.compare_digest skipped |
== on tokens leaks timing information |
secrets.compare_digest(a, b) |
Traps of modules that have their own page are listed there: collections, itertools, files and formats, logging, functools caching.
Learn more
Section titled “Learn more”- Module 09 lesson: standard library power tools and its cheat sheet
- Module 07: files and data formats and its cheat sheet
- Module 08: modules, packages and environments for
argparse,sysandtomllib - Module 06: errors and debugging for
loggingandtraceback - Module 15: performance and concurrency for
timeit,heapqand pools - Module 16: APIs and web data for HTTP clients
- OOP and data sheets: data containers, enums, ABC vs Protocol
- Master cheat sheet: files and formats, collections and comprehensions, regex, type hints, iterators and generators, errors and debugging, idioms and gotchas