I forget to mention that list.index() also uses PyObject_RichCompareBool().
Given a non-empty list *s*:
s[0] = x
assert s.index(x) == 0 # We want this to always work
or:
s = [x]
assert s.index(x) == 0 # Should not raise a ValueError
If those two assertions aren't reliable, then it's hard to correctly reason
about algorithms that use index() to find previously stored objects. This, of
course, is the primary use case for index().
Likewise, list.remove() also uses PyObject_RichCompareBool():
s = []
...
s.append(x)
s.remove(x)
In a code review, would you suspect that the above code could fail? If so, how
would you mitigate the risk to prevent failure? Off-hand, the simplest
remediation I can think of is:
s = []
...
s.append(x)
if x == x: # New, perplexing code
s.remove(x) # Now, this is guaranteed not to fail
else:
logging.debug(f"Removing the first occurrence of {x!r} the hard way")
for i, y in enumerate(s):
if x is y:
del s[i]
break
In summary, I think it is important to guarantee the identity-implies-equality
step currently in PyObject_RichCompareBool(). It isn't just an optimization,
it is necessary for writing correct application code without tricks such at the
"if x == x: ..." test.
Raymond
_______________________________________________
Python-Dev mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/NDBUPT6OWNLPLTD5MI3A3VYNNKLMA3ME/
Code of Conduct: http://python.org/psf/codeofconduct/