Unexpected behaviour from the 'in' operator
Ronald Oussoren
oussoren at cistron.nl
Mon Feb 24 13:13:15 EST 2003
On Monday, Feb 24, 2003, at 16:06 Europe/Amsterdam, sik0fewl wrote:
> Blair Hall wrote:
>> 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__.
> I don't know. It works the way I would've expected it to work.
> Because, like you said, x == y and x is in list, therefore y is in
> list.
And if you use the 'is' operator instead of __eq__ you'll get very
confusing behaviour:
id(1000) != id(500+500) # For large enough integers :-)
id("foo"+"bar") != id("foobar")
Ronald
More information about the Python-list
mailing list