API Reference¶
stamina.retry(*, on, attempts=10, timeout=45.0, wait_initial=0.1, wait_max=5.0, wait_jitter=1.0, wait_exp_base=2)
¶
Retry if one of configured exceptions are raised.
The backoff delays between retries grow exponentially plus a random jitter.
The backoff for retry attempt number attempt is computed as:
Since \(x^0\) is always 1, the first backoff is within the interval \([wait\_initial,wait\_initial+wait\_jitter]\). Thus, with default values between 0.1 and 1.1 seconds.
If all retries fail, the last exception is let through.
All float-based time parameters are in seconds.
Generators are restarted from the beginning on each retry.
Note
Being able to asend() and athrow()
into wrapped async generators introduced nontrivial complexity in the
implementation and is therefore provisional. If supporting these
features causes problems, they may be removed again in a future
version.
Warning
It is possible to get unbounded retries by passing None for
attempts (= infinite attempts) and timeout (= no timeout).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on
|
ExcOrBackoffHook
|
An Exception or a tuple of Exceptions on which the decorated callable will be retried. You can also pass a backoff hook in the form of a callable that takes an exception and returns a bool which decides whether the exception should be retried – True meaning yes. This allows more fine-grained control over when to retry. For example, to only retry on HTTP errors in the 500s range that indicate server errors, but not those in the 400s which indicate a client error. For even more control, the hook may return a float or a
There is no default for the on parameter – you must pass on explicitly. |
required |
attempts
|
int | None
|
Maximum total number of attempts. Can be combined with timeout.
|
10
|
timeout
|
float | timedelta | None
|
Maximum total time for all retries. If a backoff would end after
it, stamina gives up right away instead of waiting. Can be
combined with attempts. |
45.0
|
wait_initial
|
float | timedelta
|
Minimum backoff before the first retry. |
0.1
|
wait_max
|
float | timedelta
|
Maximum backoff time between retries at any time. |
5.0
|
wait_jitter
|
float | timedelta
|
Maximum jitter that is added to retry back-off delays (the actual jitter added is a random number between 0 and wait_jitter) |
1.0
|
wait_exp_base
|
float
|
The exponential base used to compute the retry backoff. |
2
|
Changed in 23.1.0
All time-related parameters can now be specified as a
datetime.timedelta.
Added in 23.3.0
Trio support.
Added in 24.3.0
on can be a callable now.
Added in 25.2.0
Generator functions and async generator functions are now retried, too.
Added in 25.2.0
An on backoff hook can now return a float or a
datetime.timedelta to specify a custom backoff that overrides
the default backoff.
Changed in 26.2.0
The type hints of on now accept subclasses of BaseException,
and backoff hooks are typed to receive a BaseException. This
matches the runtime behavior.
Changed in 26.2.0
If a backoff would end after timeout, stamina gives up right away. Before, it waited past timeout and attempted once more.
stamina.retry_context(on, attempts=10, timeout=45.0, wait_initial=0.1, wait_max=5.0, wait_jitter=1.0, wait_exp_base=2, *, name='<context block>')
¶
Iterator that yields context managers that can be used to retry code blocks.
Arguments have the same meaning as for stamina.retry().
name identifies this operation in retry instrumentation, including the Prometheus callable label. Use a stable name rather than per-request IDs.
Added in 23.1.0
Added in 23.3.0
Trio support.
Added in 26.2.0
The name parameter.
stamina.Attempt(attempt, next_wait_fn)
¶
A context manager that can be used to retry code blocks.
Instances are yielded by the
stamina.retry_context() iterator.
Added in 23.2.0
num
property
¶
The number of the current attempt.
next_wait
property
¶
The number of seconds of backoff before the next attempt if this attempt fails.
Warning
This value does not include a possible random jitter and is therefore just a lower bound of the actual value.
Added in 24.3.0
Changed in 25.2.0
Fixed off-by-one error when passing the attempt number to the
next_wait_fn.
stamina.RetryingCaller(attempts=10, timeout=45.0, wait_initial=0.1, wait_max=5.0, wait_jitter=1.0, wait_exp_base=2, *, name='<context block>')
¶
Call your callables with retries.
Arguments have the same meaning as for stamina.retry().
For example:
def do_something_with_url(url, some_kw):
resp = httpx2.get(url).raise_for_status()
...
rc = stamina.RetryingCaller(attempts=5)
rc(
httpx2.HTTPError,
do_something_with_url,
"https://httpbin.org/status/404",
some_kw=42,
)
# Equivalent:
bound_rc = rc.on(httpx2.HTTPError)
bound_rc(do_something_with_url, "https://httpbin.org/status/404", some_kw=42)
Both calls to rc and bound_rc run
and retry on httpx2.HTTPError.
name identifies the operation in retry instrumentation, as in
retry_context(). It also applies to callers
bound with on() and defaults to
<context block>.
Tip
Instances of RetryingCaller may be reused because they internally
create a new retry_context() iterator on
each call.
Added in 24.2.0
Added in 26.2.0
The name parameter.
__call__(on, callable_, /, *args, **kwargs)
¶
Call callable_(*args, **kwargs) with retries if on is raised.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on
|
ExcOrBackoffHook
|
Exception(s) to retry on. |
required |
callable_
|
Callable[P, T]
|
Callable to call. |
required |
args
|
args
|
Positional arguments to pass to callable_. |
()
|
kwargs
|
kwargs
|
Keyword arguments to pass to callable_. |
{}
|
on(on)
¶
Create a new instance of
BoundRetryingCaller with the same
parameters, but bound to a specific exception type.
Added in 24.2.0
stamina.BoundRetryingCaller(caller, on)
¶
Same as RetryingCaller, but pre-bound to a
specific exception type.
Caution
Returned by RetryingCaller.on() – do
not instantiate directly.
Added in 24.2.0
__call__(callable_, /, *args, **kwargs)
¶
Same as RetryingCaller.__call__(),
except retry on the exception that is bound to this instance.
stamina.AsyncRetryingCaller(attempts=10, timeout=45.0, wait_initial=0.1, wait_max=5.0, wait_jitter=1.0, wait_exp_base=2, *, name='<context block>')
¶
Same as RetryingCaller, but for async
callables.
Added in 24.2.0
Added in 26.2.0
The name parameter.
__call__(on, callable_, /, *args, **kwargs)
async
¶
Same as RetryingCaller.__call__(),
but callable_ is awaited.
on(on)
¶
Create a new instance of
BoundAsyncRetryingCaller with the
same parameters, but bound to a specific exception type.
Added in 24.2.0
stamina.BoundAsyncRetryingCaller(caller, on)
¶
Same as BoundRetryingCaller, but for
async callables.
Caution
Returned by AsyncRetryingCaller.on()
– do not instantiate directly.
Added in 24.2.0
__call__(callable_, /, *args, **kwargs)
async
¶
Same as
AsyncRetryingCaller.__call__(),
except retry on the exception that is bound to this instance.
Activation and deactivation¶
Testing¶
See also
stamina.set_testing(testing, *, attempts=1, cap=False)
¶
Activate or deactivate test mode.
In testing mode, backoffs are disabled, and attempts are set to attempts.
If cap is True, the number of attempts is not set but capped at attempts. This means that if attempts is greater than the number of attempts specified by the user, the user’s value is used.
Is idempotent and can be called repeatedly with the same values.
Added in 24.3.0
Added in 25.1.0
cap
Added in 25.1.0
Can be used as a context manager.
stamina.is_testing()
¶
Check whether test mode is enabled.
Added in 24.3.0
Instrumentation¶
See also
stamina.instrumentation.set_on_retry_hooks(hooks)
¶
Set hooks that are called after a retry has been scheduled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hooks
|
Iterable[RetryHook | RetryHookFactory] | None
|
Hooks to call after a retry has been scheduled. Passing None resets to default. To deactivate instrumentation, pass an empty iterable. |
required |
Added in 23.2.0
stamina.instrumentation.get_on_retry_hooks()
¶
Get hooks that are called after a retry has been scheduled.
Returns:
| Type | Description |
|---|---|
RetryHook
|
Hooks that will run if a retry is scheduled. Factories are called if |
...
|
they haven’t already. |
Added in 23.2.0
stamina.instrumentation.set_process_details(process_details)
¶
Set a callable that processes
RetryDetails before stamina
passes them to the retry hooks.
stamina calls it once for each scheduled retry, before it calls the
hooks. All hooks get the RetryDetails that it returns. For example, you
can use it to remove secrets from the arguments before they are logged.
Caution
Modifying args or kwargs modifies the arguments of the next attempt.
args and kwargs are the same objects that stamina passes to the
next attempt. If you change them or anything inside them, you change
the arguments of the next attempt. Build new objects instead and put
them into a new RetryDetails, for example using
dataclasses.replace().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
process_details
|
Callable[[RetryDetails], RetryDetails] | None
|
A callable that takes a |
required |
Added in 26.2.0
stamina.instrumentation.get_process_details()
¶
Get the callable that processes
RetryDetails before stamina
passes them to the retry hooks.
Returns:
| Type | Description |
|---|---|
Callable[[RetryDetails], RetryDetails] | None
|
The callable, or None if there is none. |
Added in 26.2.0
stamina.instrumentation.RetryHook
¶
A callable that gets called after an attempt has failed and a retry has been scheduled.
This is a typing.Protocol that can be implemented by any callable
that takes one argument of type
RetryDetails and returns None.
If the hook returns a context manager, it will be entered when the retry is scheduled and exited right before the retry is attempted.
For example:
def print_hook(details: stamina.instrumentation.RetryDetails) -> None:
print("a retry has been scheduled!", details)
stamina.instrumentation.set_on_retry_hooks([print_hook])
Added in 23.2.0
Added in 25.1.0
Added support for context managers.
stamina.instrumentation.RetryHookFactory(hook_factory)
dataclass
¶
Wraps a callable that returns a
RetryHook.
They are called on the first scheduled retry and can be used to delay
initialization. If you need to pass arguments, you can do that using
functools.partial().
For example, if your instrumentation needs to import a module
something_expensive which takes a long time to import, you can delay it
until the first retry (or call to
get_on_retry_hooks()):
from stamina.instrumentation import RetryDetails, RetryHookFactory
def init_with_expensive_import():
import something_expensive
def do_something(details: RetryDetails) -> None:
something_expensive.do_something(details)
return do_something
stamina.instrumentation.set_on_retry_hooks(
[RetryHookFactory(init_with_expensive_import)]
)
Added in 23.2.0
stamina.instrumentation.RetryDetails(name, args, kwargs, retry_num, wait_for, waited_so_far, caused_by)
dataclass
¶
Details about a retry attempt that are passed into
RetryHooks.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name of the callable that is being retried. |
args |
tuple[object, ...]
|
Positional arguments that were passed to the callable. |
kwargs |
dict[str, object]
|
Keyword arguments that were passed to the callable. |
retry_num |
int
|
Number of the retry attempt. Starts at 1 after the first failure. |
wait_for |
float
|
Time in seconds that stamina will wait before the next attempt. |
waited_so_far |
float
|
Time in seconds that stamina has waited so far for the current callable. |
caused_by |
BaseException
|
Exception that caused the retry attempt. |
Caution
Modifying args or kwargs modifies the arguments of the next attempt.
args and kwargs are the same objects that stamina passes to the next attempt. If you change them or anything inside them, you change the arguments of the next attempt.
Added in 23.2.0
Integrations¶
stamina.instrumentation.StructlogOnRetryHook
module-attribute
¶
Pass this object to
set_on_retry_hooks() to
activate structlog integration.
Is active by default if structlog can be imported.
See also
Added in 23.2.0
stamina.instrumentation.LoggingOnRetryHook
module-attribute
¶
Pass this object to
set_on_retry_hooks() to
activate logging integration.
Is active by default if structlog can not be imported.
See also
Added in 23.2.0
stamina.instrumentation.PrometheusOnRetryHook
module-attribute
¶
Pass this object to
set_on_retry_hooks() to
activate Prometheus integration.
Is active by default if prometheus-client can be imported.
See also
Added in 23.2.0
Exceptions¶
stamina.exceptions.TryAgain(*args, after=None)
¶
Raise this exception to force a retry, whatever on says.
attempts and timeout still apply. When they don’t allow another
attempt, stamina raises the exception that you raised TryAgain from.
Without one, the caller gets the TryAgain itself.
To keep TryAgain out of your API, always raise it from an exception.
Either the one you caught or a new one:
try:
resp = httpx2.get(url).raise_for_status()
except httpx2.TimeoutException as e:
raise TryAgain from e
if resp.json()["status"] == "pending":
raise TryAgain from JobStillPending()
Note that a new exception, like JobStillPending() here, has no traceback
until stamina raises it, so its traceback starts inside stamina.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
after
|
float | timedelta | datetime | None
|
Wait at least this long before the next attempt: a number of
seconds, a stamina adds the usual jitter to it. If the regular backoff is longer, stamina uses the regular backoff. wait_max doesn’t apply. A datetime in the past doesn’t add any wait. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If after is a naive |
Added in 26.2.0