Decorators module.

spicerack.decorators.retry(func: Optional[Callable] = None, tries: int = 3, delay: datetime.timedelta = datetime.timedelta(seconds=3), backoff_mode: str = 'exponential', exceptions: Tuple[Type[Exception], ...] = (<class 'spicerack.exceptions.SpicerackError'>,), failure_message: Optional[str] = None)Callable[source]

Decorator to retry a function or method if it raises certain exceptions with customizable backoff.


The decorated function or method must be idempotent to avoid unwanted side effects. It can be called with or without arguments, in the latter case all the default values will be used.


When the decorated function is an instance method of a class, the decorator is able to automatically detect if there is a self._dry_run property in the instance or a self._remote_hosts._dry_run one and reduce the tries attempts to 1 if it's a DRY-RUN to avoid unnecessary waits.

  • func (function, method) -- the decorated function.

  • tries (int, optional) -- the number of times to try calling the decorated function or method before giving up. Must be a positive integer.

  • delay (datetime.timedelta, optional) -- the initial delay for the first retry, used also as the base for the backoff algorithm.

  • backoff_mode (str, optional) --

    the backoff mode to use for the delay, available values are:

    constant:    delay       => 3, 3,  3,  3,   3, ...;
    linear:      delay * N   => 3, 6,  9, 12,  15, ...; N in [1, tries]
    power:       delay * 2^N => 3, 6, 12, 24,  48, ...; N in [0, tries - 1]
    exponential: delay^N     => 3, 9, 27, 81, 243, ...; N in [1, tries], delay must be > 1.

  • exceptions (type, tuple, optional) -- the decorated function call will be retried if it fails until it succeeds or tries attempts are reached. A retryable failure is defined as raising any of the exceptions listed.

  • failure_message (str, optional) -- the message to log each time there's a retryable failure. Retry information and exception message are also included. Default: "Attempt to run '<fully qualified function>' raised"


the decorated function.

Return type