Claude Code for stamina: Production Retries in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for stamina: Production Retries in Python
AI

Claude Code for stamina: Production Retries in Python

Published: January 30, 2028
Read time: 5 min read
By: Claude Skills 360

stamina provides production-safe retries. pip install stamina. Decorator: import stamina. @stamina.retry(on=httpx.HTTPStatusError). async def fetch(url): .... Sync: @stamina.retry(on=Exception). def call_api(): .... Attempts: @stamina.retry(on=Exception, attempts=5). Timeout: @stamina.retry(on=Exception, timeout=30) — total time budget. Wait: @stamina.retry(on=Exception, wait_initial=0.1, wait_max=10, wait_jitter=1). Defaults: wait_initial=0.1s, wait_max=45s, wait_factor=2 (exponential), wait_jitter=1s random jitter. Multiple exceptions: @stamina.retry(on=(httpx.HTTPStatusError, TimeoutError)). Conditional: filter by status code with a callable: @stamina.retry(on=lambda e: isinstance(e, httpx.HTTPStatusError) and e.response.status_code >= 500). Manual loop: for attempt in stamina.retry_context(on=Exception, attempts=3): with attempt: result = risky_call(). Instrumentation: stamina.instrumentation.set_on_retry_handler(handler). OpenTelemetry: from stamina.instrumentation.otel import add_retry_attributes. structlog: custom handler logs retry events. Disable in tests: stamina.set_active(False). Claude Code generates stamina retry decorators, retry_context loops, and observable retry pipelines.

CLAUDE.md for stamina

## stamina Stack
- Version: stamina >= 24.2 | pip install stamina
- Decorator: @stamina.retry(on=ExcType) | @stamina.retry(on=(A, B), attempts=5)
- Budget: timeout=30 (total seconds) | attempts=N (max tries, overrides timeout)
- Backoff: wait_initial=0.1, wait_max=45, wait_factor=2, wait_jitter=1 (defaults)
- Conditional: on=lambda e: isinstance(e, HTTPError) and e.response.status_code >= 500
- Context: for attempt in stamina.retry_context(on=Exception): with attempt: risky()
- Testing: stamina.set_active(False) — disables retries for unit tests

stamina Retry Pipeline

# app/resilient.py — stamina retry patterns for APIs, DB, and queue operations
from __future__ import annotations

import logging
import time
from typing import Any

import stamina

log = logging.getLogger(__name__)


# ─────────────────────────────────────────────────────────────────────────────
# Instrumentation — log retry attempts with structlog or stdlib logging
# ─────────────────────────────────────────────────────────────────────────────

def _on_retry(details: stamina.RetryDetails) -> None:
    """
    Called before each retry attempt.
    details: name, args, kwargs, exception, wait, attempt
    """
    log.warning(
        "retry_attempt",
        extra={
            "function":  details.name,
            "attempt":   details.attempt,
            "wait_secs": round(details.wait, 3),
            "exception": type(details.exception).__name__,
            "message":   str(details.exception),
        },
    )


stamina.instrumentation.set_on_retry_handler(_on_retry)


# ─────────────────────────────────────────────────────────────────────────────
# 1. HTTP client — retry on transient server errors
# ─────────────────────────────────────────────────────────────────────────────

class _TransientHTTPError(Exception):
    """Raised for 5xx status codes that are worth retrying."""
    def __init__(self, status_code: int, message: str) -> None:
        self.status_code = status_code
        super().__init__(f"HTTP {status_code}: {message}")


def _is_retryable(exc: Exception) -> bool:
    """Only retry on 5xx or connection errors, not 4xx client errors."""
    if isinstance(exc, _TransientHTTPError):
        return exc.status_code >= 500
    return isinstance(exc, (TimeoutError, ConnectionError))


class SimpleAPIClient:
    """API client with stamina retry on transient failures."""

    def __init__(self, base_url: str) -> None:
        self.base_url = base_url
        self._call_count = 0

    @stamina.retry(
        on=_is_retryable,
        attempts=5,
        wait_initial=0.1,
        wait_max=10.0,
        wait_jitter=0.5,
    )
    def get(self, path: str) -> dict:
        """GET request — retried up to 5 times on 5xx or connection errors."""
        self._call_count += 1
        # Simulate transient 503 on first two calls
        if self._call_count <= 2:
            raise _TransientHTTPError(503, "Service Unavailable")
        return {"data": f"result from {path}", "attempt": self._call_count}

    @stamina.retry(
        on=_is_retryable,
        timeout=30.0,          # total budget: 30s, regardless of attempt count
        wait_initial=0.2,
        wait_max=8.0,
    )
    async def async_post(self, path: str, payload: dict) -> dict:
        """Async POST — retry within a 30s total time budget."""
        import asyncio
        await asyncio.sleep(0.01)
        return {"created": True, "path": path}


# ─────────────────────────────────────────────────────────────────────────────
# 2. Database operations — retry on transient connection errors
# ─────────────────────────────────────────────────────────────────────────────

class DatabaseUnavailableError(Exception):
    pass


_db_fail_count = 0


@stamina.retry(
    on=DatabaseUnavailableError,
    attempts=4,
    wait_initial=0.5,
    wait_max=5.0,
    wait_factor=2.0,
    wait_jitter=0.2,
)
def fetch_user(user_id: int) -> dict:
    """
    DB lookup with exponential backoff:
    attempt 1, wait ~0.5s, attempt 2, wait ~1s, attempt 3, wait ~2s, attempt 4.
    wait_factor=2.0 doubles the wait each time; wait_jitter adds ±0.2s noise.
    """
    global _db_fail_count
    _db_fail_count += 1
    if _db_fail_count <= 2:
        raise DatabaseUnavailableError("connection pool exhausted")
    _db_fail_count = 0
    return {"id": user_id, "name": f"User {user_id}"}


@stamina.retry(
    on=DatabaseUnavailableError,
    attempts=3,
    wait_initial=0.1,
)
def write_event(event: dict) -> bool:
    """Write an event record — 3 attempts, fast initial retry for write idempotency."""
    # In production: INSERT with conflict handling
    return True


# ─────────────────────────────────────────────────────────────────────────────
# 3. retry_context — manual retry loop for conditional control
# ─────────────────────────────────────────────────────────────────────────────

class RateLimitError(Exception):
    def __init__(self, retry_after: float) -> None:
        self.retry_after = retry_after
        super().__init__(f"Rate limited — retry after {retry_after}s")


def call_with_rate_limit_handling(endpoint: str) -> dict:
    """
    retry_context gives a for-loop interface — useful when you need
    to inspect the exception before deciding to retry.
    """
    _attempts = 0
    for attempt in stamina.retry_context(on=Exception, attempts=5, wait_initial=0.05):
        with attempt:
            _attempts += 1
            if _attempts <= 2:
                raise RateLimitError(retry_after=0.1)
            return {"endpoint": endpoint, "result": "ok", "attempts": _attempts}
    return {}   # unreachable — stamina re-raises after max attempts


# ─────────────────────────────────────────────────────────────────────────────
# 4. Async retry — same decorator works for async functions
# ─────────────────────────────────────────────────────────────────────────────

_queue_fail = 0


@stamina.retry(
    on=ConnectionError,
    attempts=6,
    wait_initial=0.05,
    wait_max=5.0,
)
async def publish_event(topic: str, payload: dict) -> bool:
    """Async message queue publish — retried on connection drops."""
    global _queue_fail
    _queue_fail += 1
    if _queue_fail <= 3:
        raise ConnectionError("queue broker unavailable")
    _queue_fail = 0
    return True


# ─────────────────────────────────────────────────────────────────────────────
# 5. Disabling retries in tests
# ─────────────────────────────────────────────────────────────────────────────

class RetryDisabledContext:
    """Context manager that disables stamina retries — useful in tests."""

    def __enter__(self) -> "RetryDisabledContext":
        stamina.set_active(False)
        return self

    def __exit__(self, *_) -> None:
        stamina.set_active(True)


def test_fetch_user_raises_on_db_error() -> None:
    """
    stamina.set_active(False) makes @stamina.retry a no-op so the
    function raises immediately — tests check error handling, not retry behavior.
    """
    with RetryDisabledContext():
        global _db_fail_count
        _db_fail_count = 99   # force failure
        try:
            fetch_user(1)
            assert False, "should have raised"
        except DatabaseUnavailableError:
            pass   # expected
        finally:
            _db_fail_count = 0
    print("test_fetch_user_raises_on_db_error: PASS")


# ─────────────────────────────────────────────────────────────────────────────
# 6. Monitoring — count retries in Prometheus / StatsD
# ─────────────────────────────────────────────────────────────────────────────

_retry_counts: dict[str, int] = {}


def _counting_handler(details: stamina.RetryDetails) -> None:
    _retry_counts[details.name] = _retry_counts.get(details.name, 0) + 1
    # In production: prometheus_client.Counter("retries_total").labels(fn=details.name).inc()


def install_counting_instrumentation() -> None:
    """Layer a counting handler on top of the logging one."""
    original = stamina.instrumentation.get_on_retry_handler()

    def _combined(details: stamina.RetryDetails) -> None:
        if original:
            original(details)
        _counting_handler(details)

    stamina.instrumentation.set_on_retry_handler(_combined)


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    logging.basicConfig(level=logging.WARNING,
                        format="%(levelname)s %(name)s %(message)s")

    print("=== API client retry ===")
    client = SimpleAPIClient("https://api.example.com")
    result = client.get("/users/1")
    print(f"  {result}")

    print("\n=== DB retry ===")
    user = fetch_user(42)
    print(f"  {user}")

    print("\n=== retry_context manual loop ===")
    data = call_with_rate_limit_handling("/endpoint")
    print(f"  {data}")

    print("\n=== Test isolation ===")
    test_fetch_user_raises_on_db_error()

    print("\n=== Async retry ===")
    import asyncio
    ok = asyncio.run(publish_event("events", {"type": "user.created"}))
    print(f"  published: {ok}")

For the tenacity alternative — tenacity provides a rich set of stop, wait, and retry combinators (stop_after_attempt, wait_exponential_jitter, retry_if_exception_type) that compose into a fluent decorator, while stamina is a thinner wrapper with opinionated defaults (exponential backoff with jitter baked in, no combinators needed) and first-class support for the stamina.set_active(False) test-isolation pattern that tenacity requires you to mock manually, plus a structured RetryDetails object passed to the instrumentation handler instead of raw event callbacks. For the time.sleep loop alternative — a hand-rolled for attempt in range(N): try: ... except Err: time.sleep(delay * 2**attempt) loop grows in every service that needs retries, has no jitter (thundering herd on recovery), no total-budget timeout, and no observability hook, while @stamina.retry(on=Err, attempts=N) handles all of this with one line, attaches the instrumentation handler for structured logging and metrics, and the same decorator works identically for sync and async functions. The Claude Skills 360 bundle includes stamina skill sets covering @stamina.retry on single and multiple exception types, conditional on=lambda for status-code filtering, attempts vs timeout budget selection, wait_initial/wait_max/wait_factor/wait_jitter tuning, retry_context manual loop for inspection-based logic, async retry with the same decorator, set_active(False) for test isolation, custom on_retry_handler for structlog and Prometheus, counting instrumentation for retry rate dashboards, and layering multiple instrumentation handlers. Start with the free tier to try production retry 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