[Numpy-discussion] newbie question about boolean testing of array equality result
robert.kern at gmail.com
Wed Mar 23 10:59:26 EDT 2011
On Wed, Mar 23, 2011 at 09:29, Jonathan Hartley <tartley at tartley.com> wrote:
> Hey people,
> I'm writing an application in which we evaluate user-supplied Python
> Sometimes, we want to do an equality test on the result of the evaluation,
> result = eval(...)
> if result == float('nan'):
Please note that this particular expression will *never* work, even
with float objects. float('nan') != float('nan'). It's a quick of
floating point semantics.
> 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
> 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.)
def equals(x, y):
z = x == y
if not isinstance(z, bool):
# Or maybe you check for the existence of .all() or .any()
depending on which semantics you would like in the presence of numpy
z = False
> 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.
I'm afraid that it is far too late to make such a change.
"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
-- Umberto Eco
More information about the NumPy-Discussion