LoginSignup
5
5

More than 5 years have passed since last update.

retryするデコレータ

Posted at

失敗してもretryするデコレータを書いてたら、頭の体操みたいなコードができました。
機能要件は、試行の最大回数と試行の時間間隔をデコレートするときに指定できるように…

それから、下記のコードはf文字列を使っているので python3.6+です。

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"}')

実行結果は

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

実際に使うときは、ちゃんとしたライブラリを使いましょう!

5
5
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
5
5