1

I'm trying to use retry decorator. It's working well, but when the maximum retries are reached an exception teaks place. How do I avoid this exception to return well from this situation, or how to return a value when this happens?

import random
from retrying import retry

@retry( wait_fixed = 500, stop_max_delay = 2000 )
def _do_something_unreliable():
    actual = random.randint(0, 10)
    expected = 11
    print actual
    print expected
    print '=' *30
    if actual != expected:  # retry does not succeed
        raise IOError( "Broken" )

_do_something_unreliable()

The result:

3
11
==============================
7
11
==============================
2
11
==============================
5
11
==============================
Traceback (most recent call last):
  File "/home/itaybz/Documents/newKlara/infra/__stam.py", line 15, in <module>
    _do_something_unreliable()
  File "/home/itaybz/.local/lib/python2.7/site-packages/retrying.py", line 49, in wrapped_f
    return Retrying(*dargs, **dkw).call(f, *args, **kw)
  File "/home/itaybz/.local/lib/python2.7/site-packages/retrying.py", line 212, in call
    raise attempt.get()
  File "/home/itaybz/.local/lib/python2.7/site-packages/retrying.py", line 247, in get
    six.reraise(self.value[0], self.value[1], self.value[2])
  File "/home/itaybz/.local/lib/python2.7/site-packages/retrying.py", line 200, in call
    attempt = Attempt(fn(*args, **kwargs), attempt_number, False)
  File "/home/itaybz/Documents/newKlara/infra/__stam.py", line 13, in _do_something_unreliable
    raise IOError( "Broken" )
IOError: Broken
6
11
==============================

Process finished with exit code 1 
Itaybz
  • 63
  • 1
  • 6
  • 1
    That's what's supposed to happen. It reaches the stop_max_delay so it stops retrying and you get the actual result of calling the function. – jonrsharpe Sep 09 '20 at 06:31
  • You can very easily wrap the call in try/except. Or looking at the source code `retry` isn’t very complicated - you could roll your own retry that has the behaviour you want. – DisappointedByUnaccountableMod Sep 09 '20 at 06:57
  • I don't want to warp this into try and except since I want to use this in multiple functions. That would be a solution that is not clean. – Itaybz Sep 09 '20 at 09:15
  • The retry library has [unfortunately died](https://github.com/invl/retry/issues/36). As that link shows, you can use `tenacity`, or you can try out [`opnieuw`](https://github.com/channable/opnieuw), a horrible name for a package, IMHO. I am using `tenacity`, I have not used `opnieuw`, but it looks nice. I am surprised there isn't wider adoption of any of these, even `tenacity` has "only" 2800 stars. Also just my opinion, but I would use a package that seems to have decent adoption before rolling your own. That's the beauty of open source, after all. – Mike Williamson Feb 03 '21 at 10:45

0 Answers0