Skip to content

Instantly share code, notes, and snippets.

@hzhu212
Last active May 12, 2021 12:23
Show Gist options
  • Select an option

  • Save hzhu212/4b1417b32b53b07dedd091179cf58c74 to your computer and use it in GitHub Desktop.

Select an option

Save hzhu212/4b1417b32b53b07dedd091179cf58c74 to your computer and use it in GitHub Desktop.
A simple Python retrying decorator

A simple Python retrying decorator

Define:

import functools
import logging

logger = logging.getLogger(__name__)


def retry(round=3):
    """A simple retrying decorator"""
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            err = None
            for i in range(round):
                logger.debug(f'trying {func.__name__} round {i+1}/{round} ...')
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    err = e
                    continue
            raise err
        return wrapper
    return decorator

Usage:

import random

@retry(3)
def foo():
    assert random.random() > 0.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment