Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #24621
| References | <CAF_E5JYVNQmf7yptnuarqV8=aVPaix5xQg-q9bFe3Cg8wwPNYg@mail.gmail.com> <4FEC8278.7020806@mrabarnett.plus.com> |
|---|---|
| Date | 2012-06-28 17:26 +0100 |
| Subject | Re: retry many times decorator |
| From | andrea crotti <andrea.crotti.0@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1612.1340900799.4697.python-list@python.org> (permalink) |
> 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.
> --
> http://mail.python.org/mailman/listinfo/python-list
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,
func.__name__))
try:
ret = func(*args, **kwargs)
except Exception as e:
logger.error("Got exception %s with error %s" %
(type(e), str(e)))
sleep(self.timeout)
else:
return ret
attempts += 1
if attempts == self.ntimes:
logger.error("Giving up the attempts while running
%s" % func.__name__)
if self.fatal:
exit(100)
return _retry_n_times
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Re: retry many times decorator andrea crotti <andrea.crotti.0@gmail.com> - 2012-06-28 17:26 +0100
Re: retry many times decorator Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-06-28 17:43 +0000
Re: retry many times decorator Andrea Crotti <andrea.crotti.0@gmail.com> - 2012-06-28 22:11 +0100
Re: retry many times decorator andrea crotti <andrea.crotti.0@gmail.com> - 2012-06-29 09:53 +0100
Re: retry many times decorator Justin Barber <barber.justin@gmail.com> - 2012-06-29 05:45 -0700
Re: retry many times decorator Justin Barber <barber.justin@gmail.com> - 2012-06-29 05:45 -0700
csiph-web