when to use == and when to use is

G

George Trojan

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top