[Numpy-discussion] newbie question about boolean testing of array equality result

Jonathan Hartley tartley@tartley....
Wed Mar 23 09:29:18 CDT 2011


Hey people,

I'm writing an application in which we evaluate user-supplied Python 
expressions.

Sometimes, we want to do an equality test on the result of the 
evaluation, eg:

     result = eval(...)
     if result == float('nan'):
          ...

If the result is a numpy array, then this raises a ValueError, since the 
array equality operator returns a new numpy array, and the coercion of 
this to a boolean for the if predicate then explicitly raises. 
Presumably this is well-known? For us, it is undesirable.

Am I right to understand that any code which might ever encounter a 
numpy array therefore can never use an unguarded  '/if x == y:/' 
construction? Is my workaround really to replace every instance of this 
with '/if not isinstance(x, numpy.array) and x==y:/' ? This pains me, 
because otherwise this code would have no dependency on numpy. (I can't 
just prepend 'isinstance(x, float)' because, unlike the example above, 
we don't always know the type of the equality RHS until runtime.)

I can see that there's a pleasing symmetry to have all the array 
arithmetic operators and comparisons operate in an element-wise manner, 
but I think it's more important for __eq__ to follow it's usual 
semantics of returning a boolean. I'd way prefer it if the element-wise 
equality array generation was exposed as a different method.

Have I misunderstood the situation greatly? Thanks for any pointers or 
suggestions.

     Jonathan

-- 
Jonathan Hartley    tartley@tartley.com    http://tartley.com
Made of meat.       +44 7737 062 225       twitter/skype: tartley


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20110323/6f9db92c/attachment.html 


More information about the NumPy-Discussion mailing list