|
George Sakkis |
at Nov 19, 2008 at 4:05 pm
|
⇧ |
| |
On Nov 19, 10:21?am, Gilles Ganault wrote:On 19 Nov 2008 14:37:06 +0000 (GMT), Sion Arrowsmith
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