Search code examples
pythonfunctionerror-handlingerror-checkingretry-logic

How to retry only error-producing line in a function


This is quite tricky to explain, but I'd like to know if there is a way to repeatedly retry only the line of code that produced the error until it works. For example say I have the code:

def unreliabelfunction():
    #Line 1 of code
    #Line 2 of code (sometimes produces an error and sometimes works)
    #Line 3 of code

#Error handling should go where function is called, rather than inside the function.
unreliablefunction()

I would like to have some sort of error handling that would continually run line 2 until it worked (without rerunning line 1) and then continue with the rest of the function. In addition, I would like the error handling to be outside of the function and not to change the function itself.

I hope this makes sense and thank for your help :)


Solution

  • You are looking for a try: except block.

    Here's a rough example.

    def unreliabelfunction():
        line_1()
        try_wrapper(line_2())
        line_3()
    
    # Pass a function to try_wrapper
    def try_wrapper(fn, args):
        successful = False
        while not successful:
            try:
                # Execute the function.
                fn(*args)
                # If it doesn't cause an exception, 
                # update our success flag.
                successful = True
            # You can use Exception here to catch everything, 
            # but ideally you use this specific exception that occurs.
            # e.g. KeyError, ValueError, etc.
            except Exception:
                print("fn failed! Trying again.") 
    

    See the docs: https://docs.python.org/3/tutorial/errors.html#handling-exceptions