class A(object):
def __init__(self, value):
self.value = value
x = A(1)
y = A(2)
q = [x, y]
q.remove(y)
I want to remove from the list a specific object which was added before to it and to which I still have a reference. I do not want an equality test. I want an identity test. This code seems to work in both CPython and IronPython, but does the language guarantee this behavior or is it just a fluke?
The list.remove method documentation is this: same as del s[s.index(x)], which implies that an equality test is performed.
So will an object be equal to itself if you don’t override __cmp__, __eq__ or __ne__?
Yes. In your example
q.remove(y)would remove the first occurrence of an object which compares equal withy. However, the way the classAis defined, you shouldn’t† ever have a variable compare equal withy– with the exception of any other names which are also bound to the sameyinstance.The relevant section of the docs is here:
So comparison for
Ainstances is by identity (implemented as memory address in CPython). No other object can have an identity equal toid(y)withiny‘s lifetime, i.e. for as long as you hold a reference toy(which you must, if you’re going to remove it from a list!)† Technically, it is still possible to have objects at other memory locations which are comparing equal –
mock.ANYis one such example. But these objects need to override their comparison operators to force the result.