I need to compare two object instances for equality and usually I use is
when I want to do this; however after a few hours of debugging some code that fails sometimes I found this. Just a code snippet from my debugging.
print "EVENT OBJECT:", id(event.source), "AND BINDING COMPONENT:", id(self.component), "IS THE SAME:", event.source is self.component
which outputs:
EVENT OBJECT: 4 AND BINDING COMPONENT: 4 IS THE SAME: False
However, using ==
like here:
print "EVENT OBJECT:", id(event.source), "AND BINDING COMPONENT:", id(self.component), "IS THE SAME:", event.source == self.component
outputs:
EVENT OBJECT: 4 AND BINDING COMPONENT: 4 IS THE SAME: True
The result I am after is the second output.
Anyone who can explain? Thought I had it right using is
. I am quite new to Python, only started this project a few moths ago coming from .Net and C#.
Edit:
Not a duplicate of this as I thought I did know the difference between is
and ==
. In fact I did read other posts and they didn't seem to answer my question on why the code in the post behaves as it does.
Update:
Here's a snippet of the init method where I store the component.
def __init__(self, component, *bindings):
self.__dict__['component'] = component
print "COMPONENT ID:", hex(id(component)), "COMPONENT IN SELF ID", hex(id(self.component))
self.__dict__['_bindings'] = bindings
This outputs:
COMPONENT ID: 0x18 COMPONENT IN SELF ID 0x18
And then in the event handler:
print "EVENT OBJECT:", hex(id(event.source)), "AND BINDING COMPONENT:", hex(id(self.component)), "IS THE SAME:", event.source is self.component
I get this output:
EVENT OBJECT: 0x18 AND BINDING COMPONENT: 0x18 IS THE SAME: False