Reputation: 1501
I have a fairly long list of conditions that might be true in order to satisfy a particular if statement. I'm trying to debug and find out which condition was met since it shouldn't be, is there any better way than testing each condition individually? something like:
if (xpr1 or xpr2 or xpr3 .......):
print "xpr# was true"
OR better.
print "all variables" from true condition
Python 2.7
Upvotes: 0
Views: 113
Reputation: 55499
There isn't really any better way than testing each condition individually, but you can do that compactly in a list comprehension, eg:
conditions = (xpr0, xpr1, xpr2, xpr3)
print [i for i, xpr in enumerate(conditions) if xpr]
will print a list of the indices of expressions that are true. However, this won't perform the short-circuiting that you get with or
.
Of course, you can force short-circuiting by using a "traditional" for
loop, with a break
statement, eg:
for i, xpr in enumerate(conditions):
if xpr:
print i, xpr
break
although this isn't exactly the same as the short-circuiting performed by
if xpr0 or xpr1 or xpr2 or xpr3:
because we've already pre-computed all the expressions in the conditions
list.
As hiro protagonist mentions in the comments, you can test if any of those expressions are true with
any(conditions)
and that will short-circuit in the same way as the traditional for
loop code above.
FWIW, normally, one uses any
and all
on a generator expression rather than a list comp, since that avoids unnecessary evaluation of expressions after a short-circuit point is reached, but that's not applicable here.
Upvotes: 2
Reputation: 6022
>>> a = False
>>> b = True
>>> c = False
>>> print [name for name in ['a', 'b', 'c'] if locals()[name]]
['b']
Upvotes: 2