How to know the current attemp number in a Python retry decorator

Viewed 41

I am writing this python example using retry decorator. I need to print the current attemp nmber. Here in my code the tries=3 ,So I would to print if I am at the 1st , 2nd or 3rd attempt. I want to avoid implementing my own increment

 from retry import retry

 @retry(ZeroDivisionError, tries=3, delay=1)
 def ret(a,b):
         print(f'This the attempt number {attempt}')
         c=a/b
         print(c)

1 Answers

I do not see how you can do that with the retry package.

Alternatively you can create your own decorator to print the number of outputs along their execution. This should look something similar to this:

from functools import partial, wraps
import time

def retry(func=None, *, error_type=None, tries=3, delay=1):
    if not func:
        return partial(retry, error_type=error_type, tries=tries, delay=delay)
    
    @wraps(func)
    def decorator(*args, **kwargs):
        
        for num in range(tries):
            print(f'This the attempt number {num+1}') # here we print the attempt
            try: 
                out = func(*args, **kwargs)
                success = True
            except Exception as error:
                if error_type is not None and not isinstance(error, error_type):
                    success = False
                    raise error
                else:
                    success = False
                    out = error
            finally:
                if success:
                    break
                else:
                    time.sleep(delay)
        if success:
            return out
        else:
            raise out
    return decorator

now you can just use it as the one from retry package

@retry(error_type=ZeroDivisionError, tries=3, delay=1)
def ret(a,b):
    c=a/b
    return c

output

ret(8,0)
>>>
This the attempt number 1
This the attempt number 2
This the attempt number 3

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
Cell In [37], line 1
----> 1 ret(8,0)

Cell In [33], line 31, in retry.<locals>.decorator(*args, **kwargs)
     29     return out
     30 else:
---> 31     raise out

Cell In [33], line 14, in retry.<locals>.decorator(*args, **kwargs)
     12 print(f'This the attempt number {num+1}')
     13 try: 
---> 14     out = func(*args, **kwargs)
     15     success = True
     16 except Exception as error:

Cell In [36], line 3, in ret(a, b)
      1 @retry(error_type=ZeroDivisionError, tries=3, delay=1)
      2 def ret(a,b):
----> 3     c=a/b
      4     return c

ZeroDivisionError: division by zero

Related