[Numpy-discussion] arrays and __eq__

Keith Goodman kwgoodman at gmail.com
Fri Jan 1 15:23:17 EST 2010

I have a class that stores some of its data in a numpy array. I can
check for equality when myclass is on the left and an array is on the

>> m = myclass([1,2,3])
>> a = np.asarray([9,2,3])
>> m == a
   myclass([False,  True,  True], dtype=bool)

But I get the wrong answer when an array is on the left and myclass is
on the right:

>> a == m
   array([ True,  True,  True], dtype=bool)

import numpy as np

class myclass(object):

    def __init__(self, arr):
        self.arr = np.asarray(arr)

    def __eq__(self, other):
        if np.isscalar(other) or isinstance(other, np.ndarray):
            x = myclass(self.arr.copy())
            x.arr = x.arr == other
            raise TypeError, 'This example just tests numpy arrays and
        return x

    def __repr__(self):
        return 'myclass' + repr(self.arr).split('array')[1]

I've run into a similar problem with __radd__ but the solution to that
problem doesn't work for __eq__:


More information about the NumPy-Discussion mailing list