Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python establish equality between objects?

I tracked down an error in my program to a line where I was testing for the existence of an object in a list of objects. The line always returned False, which meant that the object wasn't in the list. In fact, it kept happening, even when I did the following:

class myObject(object):
    __slots__=('mySlot')
    def __init__(self,myArgument):
        self.mySlot=myArgument
print(myObject(0)==myObject(0))        # prints False
a=0
print(myObject(a)==myObject(a))        # prints False
a=myObject(a)
print(a==a)                            # prints True

I've used deepcopy before, but I'm not experienced enough with Python to know when it is and isn't necessary, or mechanically what the difference is. I've also heard of pickling, but never used it. Can someone explain to me what's going on here?

Oh, and another thing. The line

if x in myIterable:

probably tests equality between x and each element in myIterable, right? So if I can change the perceived equality between two objects, I can modify the output of that line? Is there a built-in for that and all of the other inline operators?

like image 793
John P Avatar asked Feb 22 '23 17:02

John P


1 Answers

  1. It passes the second operand to the __eq__() method of the first.

  2. Incorrect. It passes the first operand to the __contains__() method of the second, or iterates the second performing equality comparisons if no such method exists.

Perhaps you meant to use is, which compares identity instead of equality.

like image 125
Ignacio Vazquez-Abrams Avatar answered Mar 03 '23 19:03

Ignacio Vazquez-Abrams