Skip to main content

Rerun a function upon failure

Project description

Build Status codecov Python Versions pypi

Reruns a function upon failure


The function my_func will run indefinitely until it stops raising exceptions, which will never happen in this case.

from reloadable import reloadable

def my_func():
    raise Exception('Oops')

This module is useful when we want to run something forever, like a code that connects to a queue en fetches messages. Eventually it may disconnect and raise an error trying to fetch a message, so reloadable can retry connecting.

def get_message():
    conn = Queue(host='...', password='...')

    while True:
        message = conn.fetch_message()
        # probably process message afterwards...

You can config a callback function that receives an exception, which will be called if it occurs.

def shit_happens(exception):

def dont_stop():
    raise Exception('Deal with it')

You can also wait some time before the next respawn

@reloadable(sleep_time=7)  # wait 7 seconds before running `get_message` after a failure
def get_message():
    # some code...

You can always stop reloadable with a KeyboardInterrupt exception (usually triggered by ^C, but not necessarily).

Another option is to configure the stop condition exception.

def i_will_stop():
    raise ValueError('something went wrong')

Or you can define it globally, which will be used if local stop condition wasn’t defined

from reloadable import reloadable, configure


def i_will_stop():
    raise KeyError('...')

You may also want to limit the number of times that the decorator should try rerun the function

from reloadable import reloadable

def a_func():
    raise KeyError('...')

Alternatively you can disable the reloadable decorator via configuration, which is useful during unittests.

from reloadable import configure, reloadable


@reloadable()  # When disabled, it does nothing
def i_am_free():
    return '\o/'


python -m unittest -v tests


pip install reloadable

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for reloadable, version 0.1.4
Filename, size File type Python version Upload date Hashes
Filename, size reloadable-0.1.4.macosx-10.13-intel.tar.gz (3.7 kB) File type Source Python version None Upload date Hashes View
Filename, size reloadable-0.1.4-py2.py3-none-any.whl (5.6 kB) File type Wheel Python version py2.py3 Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page