boltons is a set of pure-Python utilities missing from the stdlib. pip install boltons. chunked: from boltons.iterutils import chunked; chunked(range(10), 3) → [[0,1,2],[3,4,5],[6,7,8],[9]]. windowed: windowed(range(5), 3) → [(0,1,2),(1,2,3),(2,3,4)]. bucketize: bucketize(range(5), lambda x: x%2) → {0:[0,2,4],1:[1,3]}. flatten: flatten([[1,[2,3]],[4]]) → [1,2,3,4]. remap: from boltons.iterutils import remap; remap(nested, visit=lambda p,k,v: (k, v*2 if isinstance(v,int) else v)). partition: partition(range(10), 3). first: first([None,0,False,5], key=bool) → 5. one: one([5]) → 5. unique: unique([1,2,1]). camel2under: from boltons.strutils import camel2under; camel2under("CamelCase") → “camel_case”. under2camel: reverse. slugify: slugify("Hello World!") → “hello-world”. strip_ansi: removes ANSI codes. splitlines_text: preserves line endings. is_uuid: validates UUID. atomic_save: from boltons.fileutils import atomic_save; with atomic_save("out.txt") as f: f.write("data") — write-then-rename. iter_find_files: from boltons.fileutils import iter_find_files; list(iter_find_files(".", "*.py")). LRU: from boltons.cacheutils import LRU; c = LRU(max_size=128); c["key"] = val. cachedproperty: from boltons.cacheutils import cachedproperty. parse_timedelta: from boltons.timeutils import parse_timedelta; parse_timedelta("1h 30m") → timedelta. decimal_clock: from boltons.timeutils import decimal_clock; decimal_clock() → float. clamp: from boltons.mathutils import clamp; clamp(15, 0, 10) → 10. ceil_ceil: ceil_ceil(15, 10) → 20 (ceiling to multiple). HeapQueue: from boltons.queueutils import HeapQueue; hq = HeapQueue(). ExceptionInfo: from boltons.tbutils import ExceptionInfo; ExceptionInfo.from_current(). make_sentinel: from boltons.typeutils import make_sentinel; _MISSING = make_sentinel("MISSING"). Claude Code generates boltons utility wrappers, data transformers, and safe file writers.
CLAUDE.md for boltons
## boltons Stack
- Version: boltons >= 23.0 | pip install boltons
- Iter: chunked(seq, n) | windowed(seq, n) | bucketize(seq, key) | remap(obj, visit=fn)
- Str: camel2under("CamelCase") | slugify("Hello World") | strip_ansi(text)
- File: atomic_save("path") context manager | iter_find_files(dir, "*.py")
- Cache: LRU(max_size=N) | @cachedproperty
- Time: parse_timedelta("1h 30m") | decimal_clock()
boltons Utility Pipeline
# app/utils.py — boltons iter, str, file, cache, time, math, queue, exception utilities
from __future__ import annotations
import os
import time
from pathlib import Path
from typing import Any, Callable, Iterable, TypeVar
from boltons.cacheutils import LRU, cachedproperty, cached
from boltons.fileutils import atomic_save, iter_find_files, mkdir_p
from boltons.iterutils import (
bucketize,
chunked,
first,
flatten,
one,
partition,
remap,
unique,
windowed,
)
from boltons.mathutils import clamp, ceil_ceil, floor_floor
from boltons.queueutils import HeapQueue
from boltons.strutils import (
camel2under,
slugify,
strip_ansi,
under2camel,
bytes2human,
html2text,
pluralize,
cardinalize,
ordinalize,
is_uuid,
)
from boltons.tbutils import ExceptionInfo, TracebackInfo
from boltons.timeutils import (
decimal_clock,
isoparse,
parse_timedelta,
relative_time,
StrftimeFormatter,
)
from boltons.typeutils import make_sentinel
T = TypeVar("T")
_MISSING = make_sentinel("MISSING")
# ─────────────────────────────────────────────────────────────────────────────
# 1. Sequence utilities
# ─────────────────────────────────────────────────────────────────────────────
def batch(seq: Iterable[T], size: int) -> list[list[T]]:
"""
Split iterable into fixed-size batches.
Example:
batch(range(10), 3) # [[0,1,2],[3,4,5],[6,7,8],[9]]
"""
return chunked(seq, size)
def sliding_window(seq: Iterable[T], size: int) -> list[tuple[T, ...]]:
"""
Produce overlapping windows of a sequence.
Example:
sliding_window([1,2,3,4,5], 3)
# [(1,2,3), (2,3,4), (3,4,5)]
"""
return windowed(seq, size)
def group_by(seq: Iterable[T], key: Callable) -> dict:
"""
Group items into a dict by a key function.
Example:
group_by(range(6), lambda x: x % 2)
# {0: [0,2,4], 1: [1,3,5]}
"""
return bucketize(seq, key)
def deep_flatten(nested: Any, levels: int = -1) -> list:
"""
Flatten arbitrarily nested lists.
levels=-1 means fully flatten.
Example:
deep_flatten([[1,[2,3]],[4,[5,[6]]]]) # [1,2,3,4,5,6]
"""
return flatten(nested)
def deep_map(obj: Any, fn: Callable, skip_types: tuple = ()) -> Any:
"""
Apply fn to every leaf value in a nested dict/list structure.
Example:
data = {"a": 1, "b": {"c": 2, "d": [3, 4]}}
double = deep_map(data, lambda v: v * 2 if isinstance(v, int) else v)
# {"a": 2, "b": {"c": 4, "d": [6, 8]}}
"""
def visit(path, key, value):
if isinstance(value, skip_types):
return key, value
if isinstance(value, (dict, list)):
return key, value
return key, fn(value)
return remap(obj, visit=visit)
def first_true(seq: Iterable[T], default: T | None = None, key: Callable | None = None) -> T | None:
"""
Return the first truthy element (or first where key(x) is truthy).
Example:
first_true([None, 0, "", "hello"]) # "hello"
first_true(users, key=lambda u: u.admin) # first admin user
"""
return first(seq, default=default, key=key)
def unique_by(seq: Iterable[T], key: Callable | None = None) -> list[T]:
"""
Return unique items preserving order.
key: function to extract comparison value.
Example:
unique_by([1, 2, 1, 3, 2]) # [1, 2, 3]
unique_by(users, key=lambda u: u["email"]) # dedup by email
"""
return unique(seq, key=key)
# ─────────────────────────────────────────────────────────────────────────────
# 2. String utilities
# ─────────────────────────────────────────────────────────────────────────────
def to_snake_case(s: str) -> str:
"""
Convert CamelCase or mixedCase to snake_case.
Example:
to_snake_case("CamelCase") # "camel_case"
to_snake_case("getHTTPResponse") # "get_http_response"
"""
return camel2under(s)
def to_camel_case(s: str) -> str:
"""
Convert snake_case to CamelCase.
Example:
to_camel_case("snake_case") # "SnakeCase"
"""
return under2camel(s)
def to_slug(text: str, delim: str = "-") -> str:
"""
Convert text to a URL-safe slug.
Example:
to_slug("Hello World! It's great") # "hello-world-its-great"
to_slug("Python 3.11 docs", "_") # "python_311_docs"
"""
return slugify(text, delim=delim)
def clean_terminal(text: str) -> str:
"""Remove ANSI escape codes from text."""
return strip_ansi(text)
def file_size_str(n_bytes: int) -> str:
"""
Format byte count as human-readable string.
Example:
file_size_str(1536) # "1.50 KiB"
file_size_str(1_073_741_824) # "1.00 GiB"
"""
return bytes2human(n_bytes)
def ordinal(n: int) -> str:
"""
Return the ordinal string for a number.
Example:
ordinal(1) # "1st"
ordinal(42) # "42nd"
"""
return ordinalize(n)
# ─────────────────────────────────────────────────────────────────────────────
# 3. File utilities
# ─────────────────────────────────────────────────────────────────────────────
def safe_write(path: str | Path, content: str | bytes, mode: str = "w", encoding: str = "utf-8") -> Path:
"""
Atomically write a file (write to temp + rename).
Prevents partial writes on crash.
Example:
safe_write("config.json", json.dumps(cfg))
safe_write("data.bin", binary_content, mode="wb")
"""
p = Path(path)
p.parent.mkdir(parents=True, exist_ok=True)
is_text = "b" not in mode
with atomic_save(str(p), text_mode=is_text, encoding=encoding if is_text else None) as f:
f.write(content)
return p
def find_files(
directory: str | Path,
pattern: str = "*.py",
ignored_dirs: list[str] | None = None,
) -> list[Path]:
"""
Recursively find files matching a glob pattern.
Example:
py_files = find_files("src", "*.py")
configs = find_files(".", "*.yaml", ignored_dirs=["node_modules",".git"])
"""
return [
Path(p)
for p in iter_find_files(
str(directory),
pattern,
ignored_dirs=ignored_dirs or [],
)
]
def ensure_dir(path: str | Path) -> Path:
"""Create directory and parents if they don't exist."""
p = Path(path)
mkdir_p(str(p))
return p
# ─────────────────────────────────────────────────────────────────────────────
# 4. Caching
# ─────────────────────────────────────────────────────────────────────────────
def make_lru_cache(max_size: int = 128) -> LRU:
"""
Create an LRU cache dict with a max size.
Example:
cache = make_lru_cache(256)
cache["key"] = expensive_result
hit = cache.get("key")
"""
return LRU(max_size)
class CachedLookup:
"""
Object with cached property and on-demand LRU caching.
Example:
lookup = CachedLookup(max_cache=200)
result = lookup.get("user:42", lambda: db.fetch_user(42))
"""
def __init__(self, max_cache: int = 128) -> None:
self._cache: LRU = LRU(max_cache)
self._hits = 0
self._misses = 0
def get(self, key: str, loader: Callable, ttl: float | None = None) -> Any:
if key in self._cache:
self._hits += 1
return self._cache[key]
value = loader()
self._cache[key] = value
self._misses += 1
return value
def invalidate(self, key: str) -> None:
self._cache.pop(key, None)
@cachedproperty
def stats_snapshot(self) -> dict:
return {"hits": self._hits, "misses": self._misses, "size": len(self._cache)}
# ─────────────────────────────────────────────────────────────────────────────
# 5. Time utilities
# ─────────────────────────────────────────────────────────────────────────────
def parse_duration(text: str):
"""
Parse a human duration string to a timedelta.
Example:
parse_duration("1h 30m") # timedelta(seconds=5400)
parse_duration("2 days") # timedelta(days=2)
parse_duration("90s") # timedelta(seconds=90)
"""
return parse_timedelta(text)
def human_time_ago(dt) -> str:
"""
Return human-readable relative time.
Example:
human_time_ago(datetime.utcnow() - timedelta(hours=3))
# "3 hours ago"
"""
return relative_time(dt)
def monotonic_ms() -> float:
"""Return monotonic clock time in milliseconds."""
return decimal_clock() * 1000
# ─────────────────────────────────────────────────────────────────────────────
# 6. Math and numeric
# ─────────────────────────────────────────────────────────────────────────────
def clamp_value(value: float, lo: float, hi: float) -> float:
"""
Clamp value to [lo, hi].
Example:
clamp_value(15, 0, 10) # 10
clamp_value(-5, 0, 100) # 0
clamp_value(50, 0, 100) # 50
"""
return clamp(value, lo, hi)
def round_up_to(value: float, multiple: float) -> float:
"""
Round value up to the nearest multiple.
Example:
round_up_to(13, 5) # 15
round_up_to(8, 10) # 10
round_up_to(10, 10) # 10
"""
return ceil_ceil(value, multiple)
# ─────────────────────────────────────────────────────────────────────────────
# 7. Exception utilities
# ─────────────────────────────────────────────────────────────────────────────
def format_exception() -> str:
"""
Format the current exception as a clean string (for logging/APIs).
Call inside an except block.
Example:
try:
risky()
except Exception:
error_text = format_exception()
log.error(error_text)
"""
ei = ExceptionInfo.from_current()
return str(ei)
def log_exception(logger, msg: str = "Unhandled exception") -> None:
"""
Log the current exception with boltons ExceptionInfo formatting.
"""
ei = ExceptionInfo.from_current()
logger.error("%s: %s", msg, ei)
# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
print("=== Sequence utils ===")
print(f" batch: {batch(range(9), 3)}")
print(f" window: {sliding_window(range(5), 3)}")
print(f" group_by: {group_by(range(6), lambda x: x % 2)}")
print(f" deep_flatten: {deep_flatten([[1,[2,3]],[4,[5,[6]]]])}")
data = {"a": 1, "b": {"c": 2, "d": [3, 4]}}
print(f" deep_map(*2): {deep_map(data, lambda v: v*2 if isinstance(v,int) else v)}")
print(f" unique_by: {unique_by([1,2,1,3,2])}")
print("\n=== String utils ===")
print(f" to_snake: {to_snake_case('CamelCaseHTTPResponse')}")
print(f" to_camel: {to_camel_case('snake_case_string')}")
print(f" slugify: {to_slug('Hello World! It\\'s great')}")
print(f" filesize: {file_size_str(1_500_000)}")
print(f" ordinal: {ordinal(42)}")
print("\n=== File utils ===")
import tempfile, os
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as tf:
tmp = tf.name
safe_write(tmp, "atomic content")
print(f" safe_write: {open(tmp).read()!r}")
os.unlink(tmp)
print("\n=== Math utils ===")
print(f" clamp(15, 0, 10): {clamp_value(15, 0, 10)}")
print(f" round_up_to(13, 5): {round_up_to(13, 5)}")
print(f" round_up_to(1001, 100): {round_up_to(1001, 100)}")
print("\n=== Cache ===")
cache = make_lru_cache(4)
cache["a"] = 1
cache["b"] = 2
print(f" LRU get a: {cache.get('a')}")
print(f" LRU get x: {cache.get('x', 'miss')}")
print("\n=== Time ===")
print(f" parse_duration('1h 30m'): {parse_duration('1h 30m')}")
print(f" monotonic_ms: {monotonic_ms():.1f}ms")
print("\n=== Exception info ===")
try:
raise ValueError("demo error")
except Exception:
print(f" {format_exception()[:80]}...")
For the more-itertools alternative — more-itertools is specifically focused on iterator/sequence recipes (200+ functions), and does not cover strings, file I/O, caching, or math; boltons covers a broader surface area (strings, files, time, math, caching, queues, exceptions) with fewer but more production-useful functions per category — use more-itertools when you primarily need iterator operations, boltons when you want a single package that adds useful utilities across multiple domains. For the toolz + funcy alternative — toolz and funcy focus on functional programming patterns (compose, curry, memoize, groupby); boltons focuses on practical utilities that are missing from stdlib (atomic_save, ExceptionInfo, parse_timedelta, camel2under) — use toolz/funcy for functional patterns, boltons for Python “missing batteries” utilities. The Claude Skills 360 bundle includes boltons skill sets covering batch()/sliding_window()/group_by()/deep_flatten()/deep_map()/first_true()/unique_by(), to_snake_case()/to_camel_case()/to_slug()/clean_terminal()/file_size_str()/ordinal(), safe_write()/find_files()/ensure_dir(), make_lru_cache()/CachedLookup, parse_duration()/human_time_ago()/monotonic_ms(), clamp_value()/round_up_to(), format_exception()/log_exception(). Start with the free tier to try Python utility programming and missing batteries code generation.