Simplifying if-else statement with boolean functional conditions in Python

Viewed 110

I have a series of if-else statements like this:

if funct1():
   return A
elif funct2():
   return B
elif funct3():
   return C
... etc

where funct1, funct2, funct3, etc all return booleans

I know that if the conditions of the if-else statements are possible values of a variable than a dictionary can be used to simplify the if-else statement like this:

if foo == A:
  return 1
elif foo == B:
  return 2
... etc

becomes

dict = {A: 1, B:2, ... etc }
return dict[foo]

can something similar be done for my first example involving conditionals that comprise of functions which return booleans?

2 Answers

You can make a list or dict of function-value associations, iterate through it, and return the first value whose function returns a truthy value:

for func, res in [(func1, A), (func2, B), ...]:
    if func():
        return res

This can of course be dressed up in various ways:

vals = [(func1, A), (func2, B), ...]
return next(res for func, res in vals if func())

In this case next will raise a StopIteration if no function returned something truthy, which may or may not be something you want…

You can try the built-in enumerate() function:

vals = [A, B, C]
funs = [fun1, fun2, fun3]
for i, fun in enumerate(funs):
    if fun():
        return vals[i]
Related