[PYTHON] Decorator to retry

When I wrote a decorator that would retry even if I failed, I had a code like a brain teaser. Functional requirements can be specified when decorating the maximum number of trials and the time interval between trials ...

Then the code below is python3.6 + because it uses the f string.

from functools import wraps
from time import sleep, time

def retry(count=0, delay=0):
    def _retry(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            _delay = delay
            _time = time()
            for c in range(count):
                print(f'time: {time()-_time:.1f}')
                success = func(*args, **kwargs)
                if success or c == count-1:
                    break
                sleep(_delay)
                _delay *= delay
            return success
        return wrapper
    return _retry

try_count = 0
@retry(count=3, delay=1.5)
def unstable_func(threshold):
    global try_count
    try_count += 1
    print(f'try count: {try_count}')
    return True if try_count > threshold else False

if __name__ == '__main__':
    print(f'unstable_func is {"succeeded" if unstable_func(3) else "failed"}')
    print()
    print(f'unstable_func is {"succeeded" if unstable_func(3) else "failed"}')

The execution result is

time: 0.0
try count: 1
time: 1.5
try count: 2
time: 3.8
try count: 3
unstable_func is failed

time: 0.0
try count: 4
unstable_func is succeeded

When you actually use it, use a proper library!

-pypi / retry → The documentation is concise. -pypi / retrying → Feeling rich in functions.

Recommended Posts

Decorator to retry
python decorator to retry
Decorator 1
Decorator 2
How to use the decorator
Decorator
Decorator
Decorator to silence standard output
[Introduction to Udemy Python 3 + Application] 57. Decorator
MyHDL decorator
Decorator to avoid UnicodeEncodeError in Python 3 print ()
Use the retry processing mode added to Boto3