How does Python __contains__ work for lists if I use arbitrary objects for elements?
Will it revert to the is operator? Or does it use __eq__ if provided?
A simple test gave
class Test: pass
print(Test() in [Test()]) # -> no
a=Test()
print(a in [a]) # -> yes
print(a in [Test()]) # -> no
So can I assume it uses the comparison by references is?
The default
__contains__implementation for list just compares the object with the==(__eq__) operator.It is this operator that, if not defined for a class, defaults to the behavior of
is.In short, “a in lst” is the equivalent to:
The behavior of
==does change whetheritemimplements__eq__explicitly, and defaults to object identity (is) otherwise.