Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set "in" operator: uses equality or identity?

class A(object):     def __cmp__(self):         print '__cmp__'         return object.__cmp__(self)      def __eq__(self, rhs):         print '__eq__'         return True a1 = A() a2 = A() print a1 in set([a1]) print a1 in set([a2]) 

Why does first line prints True, but second prints False? And neither enters operator eq?

I am using Python 2.6

like image 565
Gennadiy Rozental Avatar asked Feb 01 '12 01:02

Gennadiy Rozental


People also ask

What is the difference between equality and identity is operator?

The equality operator will attempt to make the data types the same before making the comparison. On the other hand, the identity operator requires both data types to be the same as a prerequisite.

Are the IS operator and == operator the same?

The 'is' is known as the identity operator. The == operator helps us compare the equality of objects. The is operator helps us check whether different variables point towards a similar object in the memory. We use the == operator in Python when the values of both the operands are very much equal.

Is identity an operator in Python?

Identity operators are used to compare the memory location of two objects, especially when both the objects have same name and can be differentiated only using its memory location. There are two Identity operators: "is" and "is not" . is - Returns true if both variables are the same object.

What is == and === in Python?

The == operator checks to see if two operands are equal by value. The === operator checks to see if two operands are equal by datatype and value.


1 Answers

Set __contains__ makes checks in the following order:

 'Match' if hash(a) == hash(b) and (a is b or a==b) else 'No Match' 

The relevant C source code is in Objects/setobject.c::set_lookkey() and in Objects/object.c::PyObject_RichCompareBool().

like image 99
Raymond Hettinger Avatar answered Sep 27 '22 23:09

Raymond Hettinger