0

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

3
  • what about any(xpr1, xpr2, ...)? to debug you could use [bool(x) for x in (xp1, xpr2, ...)]. Commented Dec 22, 2016 at 8:03
  • @hiro all() returns True, if all elements are True, if (...) from UserZer0 schould return True, if at least one element is True. Commented Dec 22, 2016 at 8:07
  • @Humbalan yes, just noticed and corrected. Commented Dec 22, 2016 at 8:08

2 Answers 2

2
>>> a = False
>>> b = True
>>> c = False
>>> print [name for name in ['a', 'b', 'c'] if locals()[name]]
['b']
Sign up to request clarification or add additional context in comments.

3 Comments

Alternatively, if typing out quotes and commas gets annoying for many variables, you can instead just write 'a b c'.split().
@AlexHall your comment massively improves the usefulness of this answer! Would not have thought about that!
Or, since they are single character names: list('abc').
2

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.

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.