python decorator to retry

from functools import wraps
import time


def retry_decorator(retry_num: int, sleep_sec: int):
    """
Returns the decorator to retry
    :param retry_num:number of retries
    :param sleep_sec:Number of seconds to sleep before retrying
    :return:Decorator
    """

    def _retry(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for retry_count in range(1, retry_num + 1):
                try:
                    ret = func(*args, **kwargs)
                    return ret
                except Exception as exp:  # pylint: disable=broad-except
                    if retry_count == retry_num:
                        print(f"Retry_count over ({retry_count}/{retry_num})")
                        raise Exception from exp
                    else:
                        print(f"Retry after {sleep_sec} sec ({retry_count}/{retry_num}). Error = {exp}")
                        time.sleep(sleep_sec)

        return wrapper

    return _retry


@retry_decorator(retry_num=3, sleep_sec=1)
def hoge():
    raise Exception("fail")


if __name__ == "__main__":
    hoge()

Execution result

Retry after 1 sec (1/3). Error = fail
Retry after 1 sec (2/3). Error = fail
Retry_count over (3/3)
Traceback (most recent call last):
  File "retry.py", line 18, in wrapper
    ret = func(*args, **kwargs)
  File "retry.py", line 35, in hoge
    raise Exception("fail")
Exception: fail

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "retry.py", line 39, in <module>
    hoge()
  File "retry.py", line 23, in wrapper
    raise Exception from exp
Exception

Recommended Posts

python decorator to retry
Decorator to retry
[Introduction to Udemy Python 3 + Application] 57. Decorator
Note: Python Decorator
Updated to Python 2.7.9
Python function decorator
"Backport" to python 2
Decorator to avoid UnicodeEncodeError in Python 3 print ()
Want to add type hints to your Python decorator?
How to install Python
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
Rewrite Python2 code to Python3 (2to3)
How to install python
Introduction to Python language
python decorator usage notes
Introduction to OpenCV (python)-(2)
Note to daemonize python
Introducing Python 2.7 to CentOS 6.6
Retry with python requests
Connect python to mysql
[Python MinMaxScaler] Normalize to 0 ~ 1
Python decorator operation memo
I tried Python> decorator
Connect to BigQuery with Python
[2020.8 latest] How to install Python
[python] Convert date to string
Post from Python to Slack
How to install Python [Windows]
Post to vim → Python → Slack
To flush stdout in Python
Convert numpy int64 to python int
python3: How to use bottle (2)
[Python] Convert list to Pandas [Pandas]
Cheating from PHP to Python
A road to intermediate Python
Try to understand Python self
Python notes to forget soon
[Python] How to use list 1
Connect to Wikipedia with Python
How to update Python Tkinter to 8.6
Post to slack with Python 3
Anaconda updated from 4.2.0 to 4.3.0 (python3.5 updated to python3.6)
Post to Twitter using Python
How to use Python argparse
Start to Selenium using python
Introduction to serial communication [Python]
Update python on Mac to 3.7-> 3.8
3 Reasons Beginners to Start Python
Convert Scratch project to Python
[Python] Convert Shift_JIS to UTF-8
Python: How to use pydub
[Python] How to use checkio
Switch from python2.7 to python3.6 (centos7)
How to run Notepad ++ Python
Speech to speech in python [text to speech]
Python higher-order function (decorator) sample
[Python] Another way to import
Connect to sqlite from python
Switch python to 2.7 with alternatives
Write to csv with Python