On 3/10/14 2:09 PM, George Trojan wrote:
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.
The last sentence seems telling to me: if you don't care if objects are
equal, then don't use ==.
Of course, a long change of if's to figure out which object you have
seems odd to me...
--Ned.
George
--
Ned Batchelder, http://nedbatchelder.com
--
https://mail.python.org/mailman/listinfo/python-list