Stdlib Essentials
High-frequency standard library modules for scripts and services. Results appear in the same fence: same-line # when short, multiline # blocks below the sample when not.
Search across all documentation pages
High-frequency standard library modules for scripts and services. Results appear in the same fence: same-line # when short, multiline # blocks below the sample when not.
Serialize and parse JSON with the json module.
import json
payload = json.dumps({"ok": True}) # '{"ok": true}'
json.loads(payload) # {'ok': True}Prefer timezone-aware datetimes (datetime.UTC on 3.11+).
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
now.tzinfo is not None # True
datetime(2020, 1, 1, tzinfo=timezone.utc).isoformat()
# '2020-01-01T00:00:00+00:00'Configure root logging once at process start.
import logging, io
buf = io.StringIO()
logging.basicConfig(level=logging.INFO, stream=buf, force=True,
format="%(levelname)s %(message)s")
logging.getLogger("app").info("started")
"INFO started" in buf.getvalue() # TrueBuild CLIs with argparse for flags and subcommands.
import argparse
p = argparse.ArgumentParser()
p.add_argument("--port", type=int, default=8000)
p.parse_args(["--port", "9000"]).port # 9000
p.parse_args([]).port # 8000Run external commands with explicit args lists (no shell) when possible.
import subprocess, sys
proc = subprocess.run([sys.executable, "-c", "print(1)"],
check=True, capture_output=True, text=True)
proc.stdout.strip() # '1'Compile hot regexes once; use raw strings.
import re
EMAIL = re.compile(r"^[\w.+-]+@[\w-]+\.[\w.-]+$")
bool(EMAIL.match("a@b.co")) # True
bool(EMAIL.match("nope")) # FalseConvert dataclasses for JSON-friendly dicts.
from dataclasses import dataclass, asdict
@dataclass
class User:
id: str
name: str
asdict(User("1", "Ada")) # {'id': '1', 'name': 'Ada'}Hash bytes for integrity checks (not password storage - use dedicated KDF).
import hashlib
hashlib.sha256(b"hi").hexdigest()[:8] # '8f434346'
len(hashlib.sha256(b"hi").hexdigest()) # 64Generate secure tokens with the secrets module.
import secrets
tok = secrets.token_urlsafe(16)
len(tok) >= 16 # TrueParse and build URLs with urllib.parse.
from urllib.parse import urlencode, urlparse
urlencode({"q": "python"}) # 'q=python'
urlparse("https://x.test/a?b=1").path # '/a'Read CSV rows as dictionaries.
import csv, io
f = io.StringIO("id,name\n1,Ada\n")
rows = list(csv.DictReader(f))
rows[0]["name"] # 'Ada'Basic stats without numpy for small lists.
from statistics import mean, median
mean([1, 2, 3]) # 2
median([1, 2, 3]) # 2Unbounded memoization for pure functions when safe.
from functools import cache
@cache
def fib(n: int) -> int:
return n if n < 2 else fib(n - 1) + fib(n - 2)
fib(10) # 55Bit flags and enums live in enum module.
from enum import Flag, auto
class Perm(Flag):
R = auto()
W = auto()
bool(Perm.R | Perm.W) # True
Perm.R in (Perm.R | Perm.W) # TrueRead TOML config with tomllib (3.11+).
import tomllib
tomllib.loads('x = 1\n') # {'x': 1}Stack versions: Python 3.14.0 (stable 3.14, maintenance 3.13) · uv 0.6+ · ruff 0.9+
Reviewed by Chris St. John·Last updated Jul 31, 2026