0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonリトライするデコレータ

Posted at
from functools import wraps
import time


def retry_decorator(retry_num: int, sleep_sec: int):
    """
    リトライするデコレータを返す
    :param retry_num: リトライ回数
    :param sleep_sec: リトライするまでにsleepする秒数
    :return: デコレータ
    """

    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()

実行結果

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
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?