Skip to content

Instantly share code, notes, and snippets.

@jakesherman
Created September 10, 2017 12:27
Show Gist options
  • Save jakesherman/447aa2162e5d03378e09960a45ad3427 to your computer and use it in GitHub Desktop.
Save jakesherman/447aa2162e5d03378e09960a45ad3427 to your computer and use it in GitHub Desktop.
Try/except decorator in Python
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
@jakesherman
Copy link
Author

Should modify this to allow you to specify which type of Exception to try again for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment