retry many times decorator

andrea crotti andrea.crotti.0 at
Thu Jun 28 18:26:36 CEST 2012

> Returning a boolean isn't very Pythonic. It would be better, IMHO, if
> it could swallow a specified exception (or specified exceptions?)
> raised when an attempt failed, up to the maximum permitted number of
> attempts. If the final attempt fails, propagate the exception.
> --

Yes right I also didn't like it..  Now it become something as below,
so I capture every possible exception (since it must be generic) and
log what exception was raised.  I'm not re-raising because if it fails
and it's fatal I should just exit, and if it's not fatal it should
just continue..

class retry_n_times:
    def __init__(self, ntimes=3, timeout=3, fatal=True):
        self.ntimes = ntimes
        self.timeout = timeout
        self.fatal = fatal

    def __call__(self, func):
        def _retry_n_times(*args, **kwargs):
            attempts = 0
            while True:
                logger.debug("Attempt number %s of %s" % (attempts,
                    ret = func(*args, **kwargs)
                except Exception as e:
                    logger.error("Got exception %s with error %s" %
(type(e), str(e)))
                    return ret

                attempts += 1
                if attempts == self.ntimes:
                    logger.error("Giving up the attempts while running
%s" % func.__name__)
                    if self.fatal:

        return _retry_n_times

More information about the Python-list mailing list