0

I have a list of functions. I would like to loop through the list and try if one of the functions goes well without error. I tried this:

list_functions = [func1(var), func2(var)]

for function in list_functions:
    try:
        function
    except:
        pass
    else:
        break

else:
    raise Exception("No function succeeded.")

But my code tries only the func1 and then fails. How can I fix my code, please?

This question did not help me: Get a Try statement to loop around until correct value obtained

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
vojtam
  • 1,157
  • 9
  • 34
  • 1
    "tries only the func1 and then falls" - because the function is called outside the `try...except` block. Your list of functions is a list of the results of calling your functions. –  Jul 22 '21 at 12:58
  • Your code is not doing what you think. Your functions are executed when you call them here: `list_functions = [func1(var), func2(var)]` – It_is_Chris Jul 22 '21 at 12:59

2 Answers2

2

First of all, please provide (and look at! ;)) the full traceback when you get an error. You would see that your func1 is not called within your try: except: block, but when you create your list_functions. It will contain the result of the calls to func1, func2, which are evaluated at that time. And since func1 returns an error, the execution stops at that point.

To fix this: you have to call your functions within the try: except: block, for example like this:

list_functions = [func1, func2]

for function in list_functions:
    try:
        function(var)
    except Exception as exc:
        pass
    else:
        break
else:
    raise Exception("No function succeeded.")

It might be a little more complex if you have variable arguments to pass to each of your methods, but that can be achieved.

Guillaume
  • 5,497
  • 3
  • 24
  • 42
1

The problem in your code is that you called every function when defining your list_functions list. Try separating the parameters into a separate list, and call each function in the for loop:

list_functions = [func1, func2]
list_vars = [var1, var2]
for function, var in zip(list_functions, list_vars):
    try:
        function(var)
    except:
        pass
    else:
        break
else:
    raise Exception("No function succeeded.")

If the parameter remains the same for every function, then the zip() method won't be necessary anymore, as well as the separate list of variables. Just:

list_functions = [func1, func2]

for function in list_functions:
    try:
        function(var)
    except:
        pass
    else:
        break

else:
    raise Exception("No function succeeded.")
Red
  • 26,798
  • 7
  • 36
  • 58