More elegant way to try running a function X times?

George Sakkis george.sakkis at
Wed Nov 19 17:05:31 CET 2008

On Nov 19, 10:21 am, Gilles Ganault <nos... at> wrote:

> On 19 Nov 2008 14:37:06 +0000 (GMT), Sion Arrowsmith
> <si... at> wrote:
> >Note very carefully that the "else" goes with the "for" and not the "if".
> Thanks guys.

And if you end up doing this for several different functions, you can
factor it out with the following decorator:

class MaxRetriesExceededError(Exception):

def retry(n):
    def decorator(f):
        def wrapper(*args, **kwds):
            for i in xrange(n):
                r = f(*args, **kwds)
                if r: return r
            raise MaxRetriesExceededError
        return wrapper
    return decorator

If the number of retries is fixed and known at "compile" time, you can
use the standard decorator syntax:

def CheckIP():

If not, just decorate it explicitly at runtime:

def CheckIP():

n = int(raw_input('Give number of retries:'))
CheckIP = retry(n)(CheckIP)


More information about the Python-list mailing list