Created
April 30, 2018 08:59
-
-
Save L3viathan/5f14608932fd583f270920ba416feb9b to your computer and use it in GitHub Desktop.
Decorator to retry a function if it fails
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
| def retry(tries): | |
| def decorator(fn): | |
| @functools.wraps(fn) | |
| def wrapper(*args, **kwargs): | |
| ex = None | |
| for i in range(tries): | |
| try: | |
| result = fn(*args, **kwargs) | |
| except Exception as e: | |
| print("Failed...") | |
| ex = e | |
| pass | |
| else: | |
| return result | |
| raise ex | |
| return wrapper | |
| return decorator | |
| if __name__ == '__main__': | |
| import random | |
| @retry(3) | |
| def faily(chance): | |
| if random.random() > chance: | |
| return True | |
| raise RuntimeError | |
| faily(0.5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment