Unexpected behaviour from the 'in' operator

Blair Hall b.hall at irl.cri.nz
Sun Feb 23 23:19:31 EST 2003


I have just noticed that the 'in' operator for lists appears to
use the __eq__ method of a class. This does not
provide the behaviour I expected when implementing
an ad hoc numeric class type.

Here is some code:

class A(object):
    def __init__(self,x):
        self.x = x

    def __eq__(self,other):
        print 'eq'
        return self.x == other
#=============================
if(__name__ == '__main__'):
    print
    x = A(1)
    y = A(1)
    lst = [x]
    print y in lst        # prints 1

The 'y in lst' expression evaluates to true here, because
both x and y are equal to the same value. However,
x and y are not the same object!  It seems to me that
the comparison should use something like the id() function
instead of __eq__.









More information about the Python-list mailing list