Skip to content

Fallback

Provides ordered execution of asynchronous fallback attempts.

execute_fallbacks(attempts, *, fallback_on_exceptions=(Exception,), non_fallbackable_exceptions=(), error_translators=()) async

Execute attempts in order until one succeeds or fallback is disallowed.

Attempts run in order and stop at the first success. Each attempt is a callable rather than a pre-created coroutine, so alternatives that are not selected never start. A failure permits fallback when any of these views matches fallback_on_exceptions: 1. The surfaced exception or an explicit __cause__ in its chain. 2. The translated exception or an explicit __cause__ in its chain.

A view matching non_fallbackable_exceptions always blocks fallback. Translators run before matching and before a failure is surfaced, so callers receive the translated error with the attempt error as its cause. Failures that match neither policy propagate immediately; when the chain is exhausted, the final surfaced error is raised.

Examples:

Use the default policy to try another operation after any ordinary exception:

async def query_primary() -> str:
    raise TimeoutError

async def query_backup() -> str:
    return "backup result"

result = await execute_fallbacks([query_primary, query_backup])

Restrict fallback to specific errors when other failures should propagate immediately:

result = await execute_fallbacks(
    [query_primary, query_backup],
    fallback_on_exceptions=(TimeoutError,),
)

Parameters:

Name Type Description Default
attempts Sequence[Callable[[], Awaitable[T]]]

Primary attempt followed by ordered fallbacks.

required
fallback_on_exceptions tuple[type[Exception], ...]

Exception types that permit trying the next attempt. Defaults to (Exception,), which permits fallback for all ordinary exceptions. Pass () to disable fallback after failures.

(Exception,)
non_fallbackable_exceptions tuple[type[Exception], ...]

Exception types that never permit fallback, even when they also match fallback_on_exceptions. Defaults to (), which excludes nothing.

()
error_translators Sequence[Callable[[Exception], Exception]]

Callables that normalize an attempt failure before matching and before it is surfaced. Defaults to (), which disables translation.

()

Returns:

Name Type Description
T T

The exact result from the first successful attempt, including falsy values.

Raises:

Type Description
CoreTypeError

If attempts, an attempt, fallback_on_exceptions, non_fallbackable_exceptions, or error_translators has an unsupported type, or if a selected attempt does not return an awaitable.

CoreValueError

If attempts is empty.

Exception

An attempt's surfaced failure when its type is not eligible or all attempts are exhausted.

CancelledError

If the caller cancels the active attempt.