More elegant way to try running a function X times?

George Sakkis george.sakkis at gmail.com
Wed Nov 19 11:05:31 EST 2008


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

> On 19 Nov 2008 14:37:06 +0000 (GMT), Sion Arrowsmith
>
> <si... at chiark.greenend.org.uk> 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):
    pass

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:

@retry(5)
def CheckIP():
   ...

If not, just decorate it explicitly at runtime:

def CheckIP():
  ...

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


HTH,
George



More information about the Python-list mailing list