Seeking deeper understanding of python equality (==)

Jonathan Kaczynski jonathan.kaczynski at guildeducation.com
Fri May 13 20:23:36 EDT 2022


Thank you for your responses, Sam and Greg.

The do_richcompare function is where my research originally took me, but I
feel like I'm still missing some pieces to the puzzle.

Here is my updated research since you posted your responses (I'll attach a
pdf copy too):
https://docs.google.com/document/d/10zgOMetEQtZCiYFnSS90pDnNZD7I_-MFohSy83pOieA/edit#
The summary section, in the middle, is where I've summarized my reading of
the source code.

Greg, your response here,

> Generally what happens with infix operators is that the interpreter
> first looks for a dunder method on the left operand. If that method
> doesn't exist or returns NotImplemented, it then looks for a dunder
> method on the right operand.

reads like the contents of the do_richcompare function.

What I think I'm missing is how do the dunder methods relate to
the tp_richcompare function?

Thank you,
Jonathan


On Fri, May 6, 2022 at 11:55 PM Greg Ewing <greg.ewing at canterbury.ac.nz>
wrote:

> On 7/05/22 12:22 am, Jonathan Kaczynski wrote:
> > Stepping through the code with gdb, we see it jump from the compare
> > operator to the dunder-eq method on the UUID object. What I want to be
> able
> > to do is explain the in-between steps.
>
> Generally what happens with infix operators is that the interpreter
> first looks for a dunder method on the left operand. If that method
> doesn't exist or returns NotImplemented, it then looks for a dunder
> method on the right operand.
>
> There is an exception if the right operand is a subclass of the
> left operand -- in that case the right operand's dunder method
> takes precedence.
>
> > Also, if you change `x == y` to `y
> > == x`, you still see the same behavior, which I assume has to do with
> > dunder-eq being defined on the UUID class and thus given priority.
>
> No, in that case the conparison method of str will be getting
> called first, but you won't see that in pdb because it doesn't
> involve any Python code. Since strings don't know how to compare
> themselves with uuids, it will return NotImplemented and the
> interpreter will then call uuid's method.
>
> --
> Greg
> --
> https://mail.python.org/mailman/listinfo/python-list
>


More information about the Python-list mailing list