I have some functions which try various methods to solve a problem based on a set of input data. If the problem cannot be solved by that method then the function will throw an exception.
I need to try them in order until one does not throw an exception.
I'm trying to find a way to do this elegantly:
try:
    answer = method1(x,y,z)
except MyException:
    try:
        answer = method2(x,y,z)
    except MyException:
        try:
            answer = method3(x,y,z)
        except MyException:
            ...
In pseudo code what I'm aiming for is something along the lines of:
tryUntilOneWorks:
    answer = method1(x,y,z)
    answer = method2(x,y,z)
    answer = method3(x,y,z)
    answer = method4(x,y,z)
    answer = method5(x,y,z)
except:
    # No answer found
To be clear: method2 mustn't be called unless method1 fails, and so on.
Given that Python functions are first class objects, you can add them to a sequence:
methods = [method1, method2, method3, ..., methodN]
Applying every item of the list to your arguments until one doesn't fail is straightforward in that case:
def find_one_that_works(*args, **kwargs):
    for method in methods:
        try:
            return method(*args, **kwargs)
        except MyException:
            pass
    raise MyException('All methods failed')
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With