Skip to content

Instantly share code, notes, and snippets.

@L3viathan
Created April 30, 2018 08:59
Show Gist options
  • Select an option

  • Save L3viathan/5f14608932fd583f270920ba416feb9b to your computer and use it in GitHub Desktop.

Select an option

Save L3viathan/5f14608932fd583f270920ba416feb9b to your computer and use it in GitHub Desktop.
Decorator to retry a function if it fails
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