Python Standard Library Patterns

itertools, functools, json, datetime, uuid, regex, subprocess, typing, and enum recipes.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Itertools and functools
Chain iterables
from itertools import chain
combined = list(chain([1, 2], [3, 4]))

# Chain iterables

Group consecutive items
from itertools import groupby
for key, group in groupby(sorted(words), key=len):
    print(key, list(group))

# Group consecutive items

Cartesian product
from itertools import product
pairs = list(product(["dev", "prod"], ["us", "eu"]))

# Cartesian product

Accumulate totals
from itertools import accumulate
running = list(accumulate([1, 2, 3, 4]))

# Accumulate totals

LRU cache
from functools import lru_cache

@lru_cache(maxsize=128)
def fib(n: int) -> int:
    return n if n < 2 else fib(n - 1) + fib(n - 2)

# LRU cache

## JSON, datetime, and UUID
Parse JSON
import json
data = json.loads(payload)

# Parse JSON

Dump JSON pretty
output = json.dumps(data, indent=2, sort_keys=True)

# Dump JSON pretty

Current UTC timestamp
from datetime import datetime, timezone
now = datetime.now(timezone.utc)

# Current UTC timestamp

Parse ISO datetime
from datetime import datetime
dt = datetime.fromisoformat("2026-03-07T12:30:00+00:00")

# Parse ISO datetime

Generate UUID
import uuid
identifier = uuid.uuid4()

# Generate UUID

## Regular expressions and subprocess
Regex find all
import re
numbers = re.findall(r"\d+", text)

# Regex find all

Regex named groups
import re
match = re.search(r"(?P<user>\w+)@(?P<host>[\w.]+)", email)
parts = match.groupdict()

# Regex named groups

Run subprocess
import subprocess
result = subprocess.run(["git", "status"], capture_output=True, text=True, check=True)
print(result.stdout)

# Run subprocess

Subprocess with shell disabled
import subprocess
subprocess.run(["ls", "-la"], check=True)

# Subprocess with shell disabled

## Typing and enums
Type alias
type UserId = int

# Type alias

Typed dict
from typing import TypedDict

class UserRow(TypedDict):
    id: int
    name: str

# Typed dict

Optional type
def find_user(user_id: int) -> str | None:
    ...

# Optional type

Generic list alias
def first(items: list[str]) -> str:
    return items[0]

# Generic list alias

Enum
from enum import Enum

class Status(Enum):
    OPEN = "open"
    CLOSED = "closed"

# Enum