Created
May 14, 2024 22:47
-
-
Save Simsso/38b1fe7a0c3a4b613094af74fed880ca to your computer and use it in GitHub Desktop.
Retry annotation for Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import functools | |
| import time | |
| def retry(max_retries=3, delay_s=2): | |
| def decorator(func): | |
| @functools.wraps(func) | |
| def wrapper(*args, **kwargs): | |
| retries = max_retries | |
| while retries > 0: | |
| try: | |
| return func(*args, **kwargs) | |
| except Exception as e: | |
| retries -= 1 | |
| print(f"Retry {max_retries - retries}/{max_retries}, Error: {e}") | |
| if retries > 0: | |
| time.sleep(delay_s) | |
| else: | |
| raise | |
| return wrapper | |
| return decorator |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example use: