Seeking deeper understanding of python equality (==)

Greg Ewing greg.ewing at canterbury.ac.nz
Fri May 6 22:24:03 EDT 2022


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


More information about the Python-list mailing list