Created
October 29, 2025 12:00
-
-
Save aanastasiou/aba770011d619cac1eebe1236f0d7f12 to your computer and use it in GitHub Desktop.
A Python decorator to retry calling functions that raise exceptions up to N times.
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
| """ | |
| Shows the use of a python decorator that re-tries calling the decorated function up to N times, before allowing | |
| the **last** exception to propagate through. | |
| """ | |
| from functools import wraps | |
| from random import random | |
| def retry_or_die(N=5): | |
| def retry_or_die_factory(fn): | |
| @wraps(fn) | |
| def wrapped_fn(*args, **kwargs): | |
| q = None | |
| for k in range(0, N): | |
| try: | |
| return fn(*args, **kwargs) | |
| except Exception as ex: | |
| print(f"OOPS {k}") # Here only for demonstration purposes | |
| q = ex | |
| raise q | |
| return wrapped_fn | |
| return retry_or_die_factory | |
| @retry_or_die(N=8) | |
| def function_with_possible_exception(a, b=2): | |
| if random() >= 0.5: # Change this threshold to cause the exception branch to be followed more frequently. | |
| raise FileNotFoundError("File not found") | |
| else: | |
| return a+b | |
| if __name__ == "__main__" | |
| print(function_with_possible_exception(12, 29)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment