Python retry decorator

A handy little piece of code to retry some function number of times. Takes number of tries and delay (in seconds) as arguments.

import time
import functools

def retry(func=None, tries=3, delay=5):
    if func is None:
        return functools.partial(retry, tries=tries, delay=delay)
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        exception = None
        for i in range(tries):
            try:
                return func(*args, **kwargs)
            except Exception as ex:
                time.sleep(delay)
                exception = ex
        raise exception

    return wrapper

Usage example:

1
2
3
4
5
6
7
8
9
import random

@retry
def foo():
    if random.randint(0, 1):
        raise Exception
    print('foo')

foo()

To use the decorator with custom tries or delay arguments just do:

1
2
3
4
5
@retry(tries=100, delay=10)
def foo():
    if random.randint(0, 1):
        raise Exception
    print('foo')
Edit

Pub: 12 Nov 2017 19:19 UTC

Edit: 12 Nov 2017 19:32 UTC

Views: 478