Claude Code for boltons: Pure Python Utilities for Every Project — Claude Skills 360 Blog
Blog / AI / Claude Code for boltons: Pure Python Utilities for Every Project
AI

Claude Code for boltons: Pure Python Utilities for Every Project

Published: June 9, 2028
Read time: 5 min read
By: Claude Skills 360

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.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free