9

Sometimes I have a situation where I want to test whether a variable is 0 or None or not. In pure Python, this is simply

foo == True

but when foo is possibly a Numpy object (such as numpy.ndarray), this does not work anymore and I get the error:

ValueError: The truth value of an array with more than one element is ambiguous. 
 Use a.any() or a.all()

and in this case I want a.any(), however this fails on non-iterable objects.

Of course I can explicitly check if foo is 0 or None, but I am wondering if there is a more elegant way to do this.

How can I check if an arbitrary object (both iterable and not) is True or not?

Tim
  • 1,466
  • 16
  • 24
  • More Pythonically, it's `if foo` - and that'll work with most things. Unfortunately, you'll have to special case `numpy.ndarray` or any other type that's more complex than 0, None, False, len() == 0 equates to False. – Jon Clements Oct 19 '12 at 12:08
  • 1
    I usually check numpy object to be None with `array is None`, but this doesn't check for zero though. See here for a similar question, http://stackoverflow.com/questions/5086178/python-how-to-check-if-array-is-not-empty – gg349 Oct 19 '12 at 14:05

2 Answers2

2

Just use np.all or np.any instead of the .all method. np.all will create an array if it is not one yet.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
seberg
  • 8,785
  • 2
  • 31
  • 30
  • 1
    Just be aware that this doesn't work as you might think for all iterables: `np.any(False for _ in range(10))` yields `True`. (Of course, it would work if this were a list comprehension instead of a generator.) Basically, it evaluates the logical truth of the iterable instance instead of making an array from the contents. You can work around this with `np.fromiter`, but it's an extra step. Still, using `np.all`, etc, is by far the cleanest solution if you just want to deal with most cases. – Joe Kington Oct 19 '12 at 14:51
  • This seems like a suitable solution, thanks! The generator exception is not really an issue for me, but it's good to know there are potential pitfalls. – Tim Oct 24 '12 at 19:12
1

The recipe I use is to surround the statement assuming the existence of a variable in a try except block:

try:
    do_something(foo)
except NameError:
    foo = something
Ben Allison
  • 7,244
  • 1
  • 15
  • 24