retry decorator at Python

1.7k Views Asked by At

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 
0

There are 0 best solutions below