Repository navigation
v0.2.1
Publishes the completed 0.2 release under a fresh version, preserving the older
v0.2.0 tag from the failed publishing attempt.
A ground-up rework and a much larger toolkit. Every decorator works on plain functions,
async def functions and methods, keeps the wrapped signature for type checkers, and never
configures logging. Several
v0.1 decorators that did not do what their names promised (transactional, revert_on_failure,
async timing) now work. See the
migration guide for the full upgrade
path.
Highlights
- Zero dependencies, fully typed.
wraptandtyping-extensionsare gone; signatures are
preserved withParamSpec, the package shipspy.typed, andmypy --strictis clean. - Sync and async with one API.
async defwrappers stay coroutine functions and never block
the event loop. - A real resilience toolkit.
retrywith backoff, jitter and hooks;CircuitBreaker;
fallback;suppress;timeoutthat actually interrupts. - A real concurrency toolkit.
memoizewith TTL and LRU,rate_limitwith a sliding window,
a sharedRateLimiter,Bulkhead,throttle,debounceandsingleflight. - Retry that honours the server.
retry(delay_from=retry_after_header)followsRetry-After,
max_time=anddeadline()cap the total time, and cancellation is never retried. - An async toolkit.
gather_limit,map_async,amap_iter,raceandrun_sync, plus
batch_calls(the DataLoader pattern) andhedge. - Policies and configuration.
policy(...)applies protections in the recommended order, and
configure()sets project-wide defaults. - Observable and testable.
count_calls, onepython_wrap.eventshook for every component,
log_context, andpython_wrap.testing(fast_mode,FakeClock,spy, pytest fixtures). - Fast. The
memoizehit path is about 9x faster and the validation and logging decorators
skip signature binding on plain calls. - Safe by default. Importing the package no longer touches the root logger, and
log_args,
auditandtraceredact secrets. - Works on Windows, and is tested on Python 3.10 to 3.14 on Linux, macOS and Windows.
Breaking changes
run_in_threadreturns aconcurrent.futures.Futureinstead of aThread. Migrate:
replace.join()with.result()(which also returns the value and re-raises errors).benchmarkis a plain function,benchmark(func, *, args=(), kwargs=None, runs=5, warmup=1) -> BenchmarkResult, instead of a decorator that silently ran the function three times per
call. Migrate: callbenchmark(func, args=(...)); usebenchmark_asyncfor coroutines.retry_on_exceptionis deprecated and now stops after 3 attempts by default (v0.1 retried
forever with no delay). Migrate: useretry(on=...), and passmax_attempts=Noneto keep the
old unlimited behaviour.rate_limitraisesRateLimitExceededinstead of a bareException. Migrate: catch
RateLimitExceeded(useexc.retry_after), or passblock=Trueto wait instead.log_args,log_returnandtracelog atDEBUGby default (log_argsusedINFO).
Migrate: passlevel=logging.INFOto keep the old level.no_debugis a deprecated no-op and will be removed in 0.3. Migrate: delete the decorator.validate_argsandcheck_typeraiseTypeErrorat decoration time for a name that is not
a parameter of the function. Migrate: fix the misspelled or stale parameter name.- Python 3.8 and 3.9 are no longer supported. Migrate: upgrade to Python 3.10 or newer, or
stay on 0.1.0. - Importing the package no longer calls
logging.basicConfig. Migrate: configure logging in
your application if you relied on python-wrap's root-logger setup.
Added
Resilience:
RetryBudget(withRetryBudgetStats): one Finagle/Envoy-style retry allowance shared
across functions, threads and event loops viaretry(budget=...),retrying(budget=...)or
configure(retry={"budget": ...}). When it is spent, retrying stops at once and emits
retry.budget_exhausted, which prevents retry storms against a failing dependency.retry_if_result=onretry/retryingretries when the function returns a matching value;
once retries run out the last value is returned.retryingblocks setattempt.result.- For
async deffunctions,retry_if,retry_if_resultandon_retrymay be async and are
awaited;async with attempt:is supported inretrying. timeout(..., cleanup_grace=)bounds async cleanup after the limit: the call is cancelled,
given the grace to finish its cleanup, thenTimeoutExpiredis raised.retry:delay_from=(with theretry_after_headerhelper forRetry-After),max_time=,
log_level=andlog_exc_info=;retry_stats(func)andRetryStats;retrying(...)/
Retryingfor retrying an inline block (for/async forwithwith attempt); retries
honourdeadline(). Cancellation,KeyboardInterrupt,SystemExitandGeneratorExitare
never retried.CircuitBreaker:success_threshold,exclude=,on_state_changeand.stats
(CircuitStats).timeoutis also a context manager (with timeout(5):/async with timeout(5):) and returns
aTimeoutobject.python_wrap.deadline(deadline(),remaining(),check()) gives code a
shared time budget, andtimeoutclamps to it.hedge(delay, max_extra=, on=): hedged requests for idempotent calls; the first success wins
and async losers are cancelled.
Async toolkit and concurrency:
periodic(interval, *, jitter=, initial_delay=, max_runs=, on_error=)runs a sync function in
a daemon thread, or an async function as a task, every N seconds without drift (missed ticks
are skipped). The function stays callable and gainsstart(),stop(),running,runs,
last_errorandrunning_in_background()for clean shutdown. Eventsperiodic.runand
periodic.failed.python_wrap.aio:gather_limit,map_asyncandamap_iter(bounded concurrency, lazy
input, ordered results; everything is cancelled and awaited on error, cancellation or early
exit),race(first success wins;RaceFailed) andrun_sync(refuses to run inside a running
loop).Bulkhead(max_concurrent, max_waiting=, timeout=, name=)for sync and async (decorator,with,
async with,.active,.waiting),limit_concurrency(n)andBulkheadFull.RateLimiter: one budget shared across functions (with,async with,acquire,
try_acquire), and several windows at once withrate_limit(limits=[(5, 1), (600, 900)]).batch_calls(max_size=, max_wait=, key=): the DataLoader pattern for sync and async code, with
de-duplication,.flush()/.aflush()/.pending, andBatchErroron contract violations.
Caching:
memoize(ttl=..., stale_ttl=...): stale-while-revalidate. Afterttla stale value is served
at once while one background refresh runs (a task for async functions, a daemon thread for
sync ones); a failed refresh keeps the stale value and is logged. Eventscache.staleand
cache.refresh_failed.memoize(store=...)and theCacheStoreprotocol: keep entries in any store (a dict, Redis,
...); thecache_*helpers work against it.memoize(per_instance=True): per-instance method caches held through weak references, so
instances stay collectable and need not be hashable.cached_property(ttl=)(thread-safe,async defgetters,invalidate()).memoize:cache_exceptions=/exception_ttl=, a per-itemttl=callable, and
cache_contains(),cache_get()andcache_parameters().
Observability, configuration and testing:
trace(otel=True, span_name=...)wraps calls in an OpenTelemetry span (sync and async) with
code.function,code.namespaceandpython_wrap.context.*attributes and exception
recording.opentelemetry-apiis imported lazily and only when asked for; python-wrap still
has no runtime dependencies.count_calls: calls, errors, in-flight, mean, p50, p95 and p99 per function.python_wrap.events:subscribe(),listening(),filter_events()andEVENT_NAMES, one hook
for retry, cache, circuit, limiter, bulkhead and timeout events (Prometheus, OpenTelemetry and
statsd recipes in the docs).log_context()/current_log_context(): contextvar fields inlog_args,log_return,
audit,traceandtimingmessages, onLogRecord.contextand onAuditRecord.context.
log_argsandauditacceptredact_extra=.policy(...)/Policy: reusable, immutable decorator bundles placed by role (observe,
validate,fallback,cache,limiter,bulkhead,breaker,retry,timeout,guard,
outer,inner) in the recommended order, with.with_();wrap_methods(*decorators, include=, exclude=, include_private=)decorates a class.python_wrap.config:configure(),configured(),get_config()andreset_config()for
project-wide defaults (logger, retry options, redaction), read at decoration time; explicit
arguments win.python_wrap.testing:fast_mode(),disable_retries(),disable_rate_limits(),
disable_caching(),overrides()(context managers and decorators),FakeClock/
fake_clock(),spy()/spy_on(),eventually()/eventually_sync(), and the pytest
fixturespw_fake_clockandpw_fast_mode(pytest_plugins = ["python_wrap.testing"]).- Typing: stacked decorators keep the exact function type (
@retryover@memoizekeeps
.cache_info()), andMemoized,Once,CircuitProtected,LimitedandCountedbind
correctly under methods and@classmethod. Typing regression tests runmypyin CI. - A cookbook of eight recipes, seven runnable
examples/, a performance page with
benchmarks/run.py, and a thread-safety stress suite (PW_STRESS=1, also run on free-threaded
3.13t and 3.14t).
Core:
- Decorated functions, including
periodicobjects andwrap_methodsclasses, pickle by
reference, so they work withmultiprocessingandProcessPoolExecutorunder the "spawn"
start method. Cache, limiter and breaker state is per worker process. retry:backoff,max_delay,jitter,on=exception filter,retry_if=predicate,
on_retry=hook receiving aRetryState, unlimited attempts (max_attempts=None), and bare
@retryusage.fallback(value)/fallback(handler=...)andsuppress(*exceptions)for failing soft.CircuitBreaker(shareable across functions), thecircuit_breakerdecorator (breaker exposed
as.breaker) andCircuitState.memoize:maxsize(LRU),ttl,typed,key=,cache_info(),cache_clear(),
cache_delete(), and in-flight de-duplication for async functions.throttle(interval),debounce(wait)with.cancel()and.flush(),singleflight(key=),
andrate_limit(block=, key=).timing(threshold=, callback=)withTimingRecord,measure_memory(callback=)with
MemoryRecord,profile(sort=, limit=, callback=), andbenchmark_async.log_argssecret redaction (redact=,DEFAULT_REDACT) andmax_length=;auditnow yields
a structuredAuditRecordwithsink=andinclude_result=;trace(limit=). Every logging
decorator acceptslogger=andlevel=.enforce_types: runtime checks from annotations (generics, unions,Literal,Annotated,
NewTypeand more) for arguments and return values.Transactionwithon_commit/on_rollback,tx=injection,current_transaction(), and
sync and async context-manager support.revert_on_failure(attrs=, deep=, target=).deprecate(since=, removed_in=, alternative=, category=), which also works on classes;
mock_data(enabled=bool | callable);compose(*decorators).- Exceptions in
python_wrap.errors, all subclassingPythonWrapError:TimeoutExpired
(also aTimeoutError),RateLimitExceeded,CircuitOpenError,ValidationError(also a
ValueError) andArgumentTypeError(also aTypeError). oncegained.reset()and.called.- A
py.typedmarker, and aNullHandleron thepython_wraplogger.
Changed
CircuitBreaker,RateLimiter,Bulkhead,RetryBudget,Transaction,Policyand
testing.FakeClockraise a clearTypeErrorwhen pickled or copied (their state belongs to
one process), instead of an error about a thread lock or a copy that silently shares a lock.RetryState.exceptioncan beNone(when a returned value was rejected by
retry_if_result), andRetryStatehas a newresultfield. A sync function given an async
retry hook raisesTypeErrorwhen decorated.- On free-threaded Python 3.14t new threads inherit the caller's context, so
log_context
fields carry over into them (sys.flags.thread_inherit_context). - The project uses a
src/layout and Hatchling, and requires Python 3.10 or newer. - The runtime dependencies
wraptandtyping-extensionswere unused and have been removed. retrywaits withasyncio.sleepforasync deffunctions, and re-raises the final
exception unchanged with its original traceback.timeoutraisesTimeoutExpired. Async functions are cancelled withasyncio.wait_for; sync
functions are interrupted withSIGALRMon the Unix main thread. The thread fallback used
elsewhere cannot stop the work, and is now documented.memoizeandcachekeys are bound to the function signature with defaults applied, so
f(1),f(x=1)andf(1, y=<default>)share one entry; list, dict and set arguments are
converted to hashable keys.deprecatepoints its warning at the caller and sets__deprecated__(PEP 702).from python_wrap.decorators import ...still works through a compatibility module.timeout(...)now returns aTimeoutobject, which is both a decorator and a context manager.
Decorator use is unchanged.retrynever retries cancellation-type exceptions (asyncio.CancelledError,
KeyboardInterrupt,SystemExit,GeneratorExit), even ifon=lists them.- The
redact=default onlog_argsandauditisNone, which means "the configured value, or
DEFAULT_REDACT". Passredact=()to turn redaction off. auditwith nosinkand a disabled log level builds no record at all.Limited.bulkheadis a read-only property.- Test overrides apply only to backoff waits.
fast_mode()andfake_clock()no longer shorten
limits on how long to wait: asyncBulkhead/limit_concurrencytimeouts,race(timeout=),
asynchedgedelays and asyncbatch_calls/debouncewindows run on real time, like their
sync versions andtimeout. - Under
fast_mode(), a blocking rate limiter (block=True) that would wait lets the call
through at once and still counts it.
Fixed
-
Final releases now pass through TestPyPI and an installation check before PyPI.
Both indexes are verified after upload before creating the GitHub release. -
Source distributions include the examples and benchmark script used by their tests.
-
Release smoke checks validate metadata, public imports,
py.typed, retry, memoization
and async behavior in an isolated installed environment. -
AsyncPeriodic.stop()no longer swallows a cancellation aimed at the task awaiting it, and
ends a loop whose run swallows the cancel;stop()called inside a run ends the loop as soon
as that run returns. -
timeout(..., cleanup_grace=...)lets an outside cancellation propagate asCancelledError
(matchingasyncio.timeout), and waits for and retrieves the child task when the caller is
cancelled instead of logging "Task exception was never retrieved". -
periodic(on_error="raise")logs an error thatstop()never collected whenstart()is
called again, instead of dropping it silently. -
revert_on_failurenever restored anything because its snapshot was always empty. -
transactionalwas a no-op; it now commits and rolls back through aTransaction. -
memoizeandcachebuilt keys fromstr(args), which collided and ignored keyword
equivalence.cache()also shared a single store across all functions it decorated. -
timingmeasured about zero seconds forasync deffunctions, and now usesperf_counter. -
measure_memoryusedru_maxrss, which is Unix-only and reported the wrong units; it now
usestracemalloc. -
The package failed to import on Windows because it imported the Unix-only
resourcemodule. -
auditreported the wrapper's own frame as the caller. -
oncewas not thread-safe, and now retries after an exception. -
validate_argsrebuilt the function signature on every call. -
Under
fast_mode()orfake_clock(), async bulkhead andracetimeouts expired at once and
hedgelaunched every backup attempt immediately. -
A blocking
RateLimiter/rate_limit(block=True)busy-spun at full CPU underfast_mode(). -
timeout's thread fallback reported a call as late when it advanced the fake clock (for
example aretryinside it), and a nested signal-basedtimeoutdid not fire under
fake_clock(). -
@transactionalon a function with a positional-only (or*tx/**tx)txparameter
crashed at call time; it now raisesTypeErrorwhen decorating. -
singleflight's default key treatedf(1, b=2)andf((1,), (("b", 2),))as the same call,
andmemoizeon a callable without an inspectable signature treatedf(1, b=2)and
f(1, 2)as the same call.
Performance
- Async
memoizeandcachehits are about 30-35% faster (one lock instead of two). - The
memoizehit path is about 9x faster. validate_args,check_type,enforce_types,log_argsandauditskip signature binding on
plain positional calls (5x to 40x faster).auditskips building a record when nobody would receive it, andtimingskips formatting
when its log level is disabled.- Numbers and a benchmark script are on the
performance page.
Deprecated
retry_on_exception: useretry(on=...). Emits aDeprecationWarning.no_debug: a no-op, to be removed in 0.3.cache: soft-deprecated in the docs only (no warning yet); prefermemoize(ttl=...).
Removed
- Support for Python 3.8 and 3.9.
- Poetry as the build and dependency tool (replaced by Hatchling and uv).
- The Sphinx documentation (replaced by the new documentation site).
- The token-based PyPI publish workflow (replaced by tag-driven publishing with Trusted
Publishing).
Infrastructure
- CI runs ruff,
mypy --strict, the test suite on Linux, macOS and Windows across Python 3.10 to
3.14, the test and thread-safety stress suites on free-threaded Python 3.14t, and a wheel
check. - Tag-driven releases publish to PyPI through Trusted Publishing, with no stored token.
- The documentation build is checked in CI and hosted on Read the Docs.
- Added Dependabot, issue and pull request templates,
CONTRIBUTING.md,SECURITY.md,
CODE_OF_CONDUCT.mdandRELEASING.md.
Known limitations
- The
timeoutthread fallback (Windows, non-main threads) cannot stop the running work. rate_limit,throttleanddebounceshare state across instances when used on methods
(rate_limitacceptskey=to split it).memoizeon methods keeps instances alive; usemaxsizeorttl.- Concurrent calls to
measure_memoryshare one tracker, andprofileon an async function
includes event-loop work. transactionalinjectstx=by keyword, so declaretxlast or keyword-only.