Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying different functions until one does not throw an exception

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.

like image 302
Mark Rogers Avatar asked Sep 13 '19 16:09

Mark Rogers


1 Answers

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')
like image 133
Mad Physicist Avatar answered Oct 08 '22 09:10

Mad Physicist