Created
September 10, 2017 12:27
-
-
Save jakesherman/447aa2162e5d03378e09960a45ad3427 to your computer and use it in GitHub Desktop.
Try/except decorator in Python
This file contains 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 try_except(func): | |
"""Try/Except decorator - takes as input a function, and outputs | |
a modified version of that function whose first argument is how | |
many times you want to re-run the function if any exception is | |
raised. | |
""" | |
def try_except_function(num_tries, *args, **kwargs): | |
"""Modified version of func - see docstring for try_except(). | |
""" | |
for i in range(num_tries): | |
try: | |
results = func(*args, **kwargs) | |
break | |
except: | |
if (i + 1) == num_tries: | |
raise | |
else: | |
pass | |
return results | |
return try_except_function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should modify this to allow you to specify which type of Exception to try again for.