The resilience and concurrency toolkit you add to every Python project. Retry (with Retry-After), circuit breaker, timeout, cache, rate limit, bulkhead, batching, async helpers, metrics and test helpers. One import, sync and async, zero dependencies. Documentation · Cookbook · Performance · Migration guide · Changelog Why python-wrap One import for the things every project hand-writes. Retry, circuit breaker,…
The resilience and concurrency toolkit for every Python project: retry, circuit breaker, timeout, cache, rate limit, bulkhead, batching, async helpers and test helpers. Typed, sync and async, zero dependencies.
The resilience and concurrency toolkit you add to every Python project.
Retry (with Retry-After), circuit breaker, timeout, cache, rate limit, bulkhead, batching, async helpers, metrics and test helpers. One import, sync and async, zero dependencies.
One import for the things every project hand-writes. Retry, circuit breaker, timeout, cache, rate limit, bulkhead, batching, bounded gather, metrics and test helpers, designed to stack and to be tested together.
Resilience that behaves.retry honours Retry-After, a time budget and cancellation; a shared deadline() caps a whole request; policy(...) stacks the protections in the right order for you.
Zero dependencies. Pure Python, nothing to audit or pin.
Typed. Decorators preserve the wrapped signature (ParamSpec), and stacking keeps the exact type (@retry over @memoize still has .cache_info()). Ships py.typed, checked with mypy --strict.
Sync and async, one API. Works on def, async def and methods. Async wrappers stay coroutine functions; built-in async paths avoid blocking the event loop. Synchronous external cache stores need the documented I/O care.
Fast. Cache hits and validation skip signature binding on the hot path (numbers).
Observable and testable. One event stream for retries, cache, circuit, limiters and timeouts; python_wrap.testing makes tests instant and deterministic.
Never configures your logging, is thread-safe, and is tested on Python 3.10 to 3.14 on Linux, macOS and Windows.
Policy.explain(), python -m python_wrap doctor (unbounded or non-idempotent retries, missing timeouts/budgets, misordering)
HTTP clients
python_wrap.http: method-safe retrying transports for httpx, a requests adapter, http_retry for aiohttp; HttpPolicy(propagate=True) carries request ids and deadlines
AgentsGuard: tool timeouts, idempotency, approval, loop detection that also covers sub-agents
pydantic-ai
PythonWrapCapability, guard_tool: idempotent tools, a usage bridge into Budget, audit hooks
Any agent or MCP host
EffectLedger (no double-fired side effects after a crash), mcp_guard, validated() repair cap, Cassette record/replay, SharedTokenWindow across workers
Adapters read the SDKs by shape and are optional; install extras such as
pip install --pre "python-wrap[openai]" only to run the contract tests. Runnable projects
live in examples/projects/ and examples/sdk_adapters/.
No provider SDK is imported: responses and errors are read by duck typing, so it works with
any client. See AI and agents
and the examples/ folder.
Install the beta with pip install --pre python-wrap. See the
changelog for details.
New in 0.3
The toolkit now includes production integration helpers alongside the existing decorators:
Dynamic switch, timed, explicit health registry and optional OpenTelemetry adapter
The package still has no runtime dependencies. Optional adapters use your application’s
existing Redis client, SQLAlchemy engine, framework or OpenTelemetry providers. Distributed
leases and stored results do not promise exactly-once external side effects after a crash
or lease expiry. Read the 0.3 migration guide
for redaction matching changes, unknown cache counts and worker lifecycle.
30-second tour
import asyncio
import time
from python_wrap import (
CircuitBreaker, gather_limit, memoize, policy, rate_limit, retry, retry_after_header, timeout,
)
from python_wrap.testing import fast_mode
# One reusable stack for a flaky HTTP dependency. Roles decide the order, not you.
http = policy(
cache=memoize(ttl=60, maxsize=256), # hits skip everything below
breaker=CircuitBreaker(failure_threshold=5, recovery_timeout=30, name="api"),
retry=retry(max_attempts=4, delay=0.5, backoff=2, jitter=0.1,
on=ConnectionError, delay_from=retry_after_header, max_time=20),
timeout=timeout(5), # per attempt
name="http",
)
@http
def fetch_user(user_id: int) -> dict[str, int]:
return {"id": user_id} # your real HTTP call goes here
print(fetch_user(1), fetch_user(1)) # the second one is a cache hit
print(fetch_user.cache_info()) # the cache API survives the stack
@rate_limit(100, 1.0, block=True) # at most 100 calls per second, waits when full
async def fetch_async(user_id: int) -> dict[str, int]:
await asyncio.sleep(0.01)
return {"id": user_id}
async def main() -> None:
# 50 requests, never more than 20 in flight; results come back in order.
users = await gather_limit(*(fetch_async(i) for i in range(50)), limit=20)
print(len(users), "users")
asyncio.run(main())
# In tests, every wait is instant but retries still run the configured number of times.
calls = []
@retry(max_attempts=4, delay=30, backoff=2, on=ConnectionError)
def flaky() -> str:
calls.append(1)
if len(calls) < 4:
raise ConnectionError
return "ok"
start = time.monotonic()
with fast_mode():
assert flaky() == "ok" # would take 30 + 60 + 120 seconds
print(f"{time.monotonic() - start:.2f}s")
What is in the box
Everything below is importable from python_wrap unless a module is shown. Choose a decorator is the quick way in.
Skip waits, cap retries, switch limiters and caches off
FakeClock, fake_clock, spy, spy_on, eventually
Control time, record calls, wait for background work; pytest fixtures pw_fake_clock, pw_fast_mode
Dev tools
deprecate, mock_data, compose, wrap_methods
Deprecation warnings at the caller, fixed test data, decorator bundles, decorate a whole class
Exceptions live in python_wrap.errors and at the top level: PythonWrapError, TimeoutExpired (a TimeoutError), RateLimitExceeded, CircuitOpenError, BulkheadFull, BatchError, ValidationError (a ValueError) and ArgumentTypeError (a TypeError).
Highlights
Retry, Retry-After and fail-soft
from python_wrap import RetryState, retry
def note(state: RetryState) -> None:
print(f"attempt {state.attempt} failed: {state.exception!r}")
calls = 0
@retry(
max_attempts=5,
delay=0.01, # wait before the 2nd attempt
backoff=2.0, # then 2x longer each time
max_delay=0.1, # but never more than this
jitter="full", # spread workers across the entire backoff interval
max_time=5, # and never spend longer than this in total
on=(ConnectionError, TimeoutError),
retry_if=lambda exc: "temporary" in str(exc),
on_retry=note,
)
def flaky() -> str:
global calls
calls += 1
if calls < 3:
raise ConnectionError("temporary glitch")
return "ok"
print(flaky()) # ok, after two retries
Fail soft with fallback(value) or suppress(OSError). The last exception is re-raised unchanged once attempts run out. max_attempts=None retries forever. Cancellation (asyncio.CancelledError, KeyboardInterrupt) is never retried. Add delay_from=retry_after_header to wait exactly as long as a 429/503 Retry-After header says, and retry a block of code with for attempt in retrying(...).
Circuit breaker, timeout and deadline
import time
from python_wrap import CircuitBreaker, CircuitOpenError, CircuitState, TimeoutExpired, deadline, timeout
payments = CircuitBreaker(failure_threshold=2, recovery_timeout=30, name="payments")
@payments
def charge(amount: int) -> str:
raise ConnectionError("gateway down")
for _ in range(2):
try:
charge(10)
except ConnectionError:
pass
try:
charge(10)
except CircuitOpenError:
print("failing fast, circuit is", payments.state.value) # no call was made
assert payments.state is CircuitState.OPEN
@timeout(1)
def step(seconds: float) -> None:
time.sleep(seconds)
try:
with deadline(0.05): # one budget for everything inside; timeouts clamp to it
step(0.01)
step(1)
except TimeoutExpired:
print("out of time")
After recovery_timeout the breaker goes half-open and lets a trial call through. Share one CircuitBreaker across functions for one dependency, or use @circuit_breaker(...) for a private one (func.breaker). timeout interrupts sync code with SIGALRM on the Unix main thread, cancels async def with asyncio.wait_for, and elsewhere falls back to a thread that cannot stop the work (see Limitations).
Caching
from python_wrap import memoize
@memoize(maxsize=128, ttl=30)
def square(n: int, *, scale: int = 1) -> int:
return n * n * scale
square(3)
square(n=3) # same entry: arguments are bound to the signature
square(3, scale=1) # still the same entry
print(square.cache_info()) # 2 hits, 1 miss
square.cache_delete(3) # drop one entry
square.cache_clear() # drop everything
cached_property(ttl=) does the same for attributes. Keys are built from the bound signature, lists, dicts and sets are converted automatically, and exceptions are not cached unless you ask (cache_exceptions=True, exception_ttl=). Concurrent awaits of the same missing key in an async def share one in-flight task. On methods the cache keeps instances alive, so give it maxsize or ttl.
Async toolkit, bulkheads and batching
import asyncio
from python_wrap import Bulkhead, BulkheadFull, batch_calls, map_async, race
queries: list[list[int]] = []
@batch_calls(max_size=100, max_wait=0.005) # the DataLoader pattern
async def get_user(ids: list[int]) -> dict[int, str]:
queries.append(ids) # one round trip for the whole batch
return {i: f"user{i}" for i in ids}
db = Bulkhead(2, max_waiting=1, name="db") # 2 running, 1 queued, the rest rejected
@db
async def query(n: int) -> int:
await asyncio.sleep(0.01)
return n
async def main() -> None:
users = await asyncio.gather(get_user(1), get_user(2), get_user(1))
assert users == ["user1", "user2", "user1"] and queries == [[1, 2]]
doubled = await map_async(lambda n: query(n * 2), range(3), limit=2)
assert doubled == [0, 2, 4]
results = await asyncio.gather(*(query(n) for n in range(4)), return_exceptions=True)
assert isinstance(results[3], BulkheadFull)
async def slow() -> str:
await asyncio.sleep(1)
return "slow"
async def fast() -> str:
return "fast"
assert await race(slow(), fast()) == "fast" # the loser is cancelled
asyncio.run(main())
Every helper cancels and awaits the tasks it started, so nothing leaks on error or cancellation. Also see hedge for backup requests on slow reads and run_sync for calling async code from scripts.
Rate limits, throttle and debounce
from python_wrap import RateLimitExceeded, RateLimiter, rate_limit
@rate_limit(2, 0.2, key=lambda user, *_: user) # 2 calls / 0.2 s, per user
def send(user: str, text: str) -> str:
return f"{user}: {text}"
send("ann", "a")
send("ann", "b")
try:
send("ann", "c")
except RateLimitExceeded as exc:
print(f"slow down, retry in {exc.retry_after:.2f}s")
send("bob", "hello") # different key, different budget
github = RateLimiter(5, 1.0, name="github") # one budget shared by several functions
@github
def get_repo(name: str) -> str:
return name
rate_limit(block=True) waits instead of raising (with await for async def), and limits=[(5, 1), (600, 900)] enforces several windows at once. throttle and debounce cover “at most once per interval” and “after the burst settles”. The sliding window never lets a 2 * calls burst through at a window edge.
Parameters whose names contain password, token, secret, api_key and similar (DEFAULT_REDACT) are masked in log_args and audit; extend with redact_extra= or project-wide through configure(redact_extra=...). For custom rules use validate_args(x=lambda x: x > 0).
Transactions and defaults
@transactional gives a function a tx: Transaction (declare it last or keyword-only) to register on_commit and on_rollback callbacks; current_transaction() reaches it from anywhere. configure(logger=..., redact_extra=...) sets project-wide defaults read at decoration time, and explicit arguments always win.
Stacking decorators and policies
Decorators are applied bottom-up and run top-down, so order matters:
Put this…
…outside of this
Because
memoize
retry, rate_limit, timeout
Cache hits skip everything; only misses pay
retry
timeout, circuit_breaker, rate_limit
Each attempt gets its own deadline
circuit_breaker
retry or timeout
The breaker counts calls whose retries were used up
fallback
retry, circuit_breaker
Fall back only after retries are exhausted or the circuit is open
log_args, timing, audit
everything
They observe what callers actually experience
enforce_types, validate_args
the rest
Reject bad input before doing any work
You do not have to memorise this. policy(observe=, validate=, fallback=, cache=, limiter=, bulkhead=, breaker=, retry=, timeout=, guard=) takes each decorator by role and applies them in the recommended order, whatever order you wrote them in. Policies are immutable (.with_(timeout=timeout(30))), work on methods and async def, and wrap_methods(policy) protects a whole class. compose(a, b, c)(f) is a(b(c(f))) when you just want a named stack. Details: Stacking and Policies.
How it compares
python-wrap is a broad toolkit; the others are deeper in one area. Use them when that one area is all you need and you want the specialist.
You need very rich retry policies: composable stop/wait strategies, per-call overrides
retry covers the common cases (backoff, jitter, Retry-After, time budget, hooks, async) with a flat signature, and shares a deadline, breaker and events with the rest
A plain lru_cache or cache on a sync function with hashable arguments is enough. Prefer it for that
Adds TTL, async, unhashable arguments and cache_delete
None of them cover bounded gather, bulkheads, batching, hedging, policies or test helpers; python-wrap trades per-area depth for one consistent, typed, dependency-free API.
0.2.0 fixes decorators that did not do what their names promised (transactional, revert_on_failure, async timing) and makes a few breaking changes: run_in_thread returns a Future, benchmark is a function, retry_on_exception is deprecated and bounded, rate_limit raises RateLimitExceeded, and the logging decorators default to DEBUG. Python 3.8 and 3.9 are no longer supported. from python_wrap.decorators import ... still works. See the migration guide.
Security
python-wrap has no runtime dependencies and makes no network calls of its own. Optional stores (Redis, SQLite) and exporters only talk to services you configure. Logging helpers redact secrets by default (password, token, api_key, …), and cache keys and idempotency keys are never logged raw. Read the threat model before sharing caches or breaker state across trust boundaries, and report vulnerabilities privately as described in SECURITY.md.
Limits
In-process by default: caches, rate limits and circuit breakers are per process unless you opt into a shared store (RedisStore, SQLiteBreakerState).
Retries are only safe for idempotent work; python -m python_wrap doctor flags risky stacks.
Sync timeouts use SIGALRM on the Unix main thread; elsewhere a worker thread is used and cannot be stopped, so make long work cooperative.
The API of the stable core is frozen ahead of 1.0; other modules may still change between minor releases.
Bug reports, ideas and pull requests are welcome. Read CONTRIBUTING.md for the development setup and checks, and SECURITY.md for reporting vulnerabilities.
评论