0

I have to use a function (myAPI.readArr) that returns a scalar,numpy.ndarray or Py_None on failure.

This works for a failure:

data = myAPI.readArr(arg1, arg2)
if not data:
   raise Exception("Problem!")

but for valid arguments I get:

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

How can I check that the call succeeded or not?

Peter Petrik
  • 9,701
  • 5
  • 41
  • 65
  • PEP 8 explicitly recommends testing `is None` when you mean `is None`, in part because many objects besides `None` are falsey—like, say, `False`. The fact that some objects are illegal to test for falsiness, like NumPy arrays, just means that you get an early error message for your mistake instead of code that seems to work until you deploy it and it silently screws up your data. :) – abarnert Apr 20 '15 at 08:34
  • I think [this](http://stackoverflow.com/questions/14247373/python-none-comparison-should-i-use-is-or) is the canonical answer, but the linked one seems to more directly answer the OP's question. – abarnert Apr 20 '15 at 08:36

2 Answers2

3
data = myAPI.readArr(arg1, arg2)
if data is None:
   raise Exception("Problem!")

This answer contains more details about comparison to None

Community
  • 1
  • 1
Konstantin
  • 24,271
  • 5
  • 48
  • 65
3
if data is None:
    raise Exception("Problem!")

Testing is None is better because it returns True if and only if the value is None, not if it evaluates to zero.

Jérôme
  • 13,328
  • 7
  • 56
  • 106