1

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 2

2

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…

Sign up to request clarification or add additional context in comments.

1 Comment

I wrote something extremely similar so I don't think it's worth posting as an answer, but maybe worth pointing out that a) next takes a second optional default argument, which is returned in the case nothing matches, and b) there's not really anything terribly wrong with the elif chain unless it gets long or you find it benificial to separate out the policy as data (e.g. maybe to make it easier to swap in different policies).
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.