osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

when to use == and when to use is


I know this question has been answered: 
http://stackoverflow.com/questions/6570371/when-to-use-and-when-to-use-is , 
but I still have doubts. Consider the following code:

class A:
     def __init__(self, a):
         self._a = a
     #def __eq__(self, other):
     #    return self._a != other._a

obj_0 = A(0)
obj_1 = A(1)
obj_2 = A(2)

obj = obj_1

if obj == obj_0:
     print(0)
elif obj == obj_1:
     print(1)
elif obj == obj_2:
     print(2)

if obj is obj_0:
     print(0)
elif obj is obj_1:
     print(1)
elif obj is obj_2:
     print(2)

Both if statements work, of course. Which is more efficient? My use-case 
scenario are matplotlib objects, the __eq__ operator might involve a bit 
of work. The "if" statement is a selector in a callback. I know that obj 
is one of obj_0, ..., or none of them. I do not care if obj_1 is equal 
to obj_2.

George