Is this a bug? (__eq__, __lt__, etc.)

Tim Peters tim.one at home.com
Mon May 7 22:44:12 EDT 2001


[Edw88253]
> The __eq__, __gt__, etc. methods seem to be called more often than
> necessary when I compare two objects.  Is this a bug or a feature?

So long as you get the right answer, it's neither:  it's an internal
implementation detail.

> (See transcript below)  If it's a feature, what's it accomplishing?

Sorry, but implementation details can be very tedious to explain.  If you're
curious enough, you can figure it out yourself from studying the source code.
Generally speaking, A == B gives A.__eq__(B) a chance, then B.__eq__(A) a
chance, then falls back to assorted ways of trying to deduce the correct
result via legacy 3-way comparisons, incl. *simulating* 3-way comparisons via
the __eq__ etc methods again.  Since you define every relevant method but
return NotImplemented from every one of them, you force Python to try every
way to come up with a meaningful result it can think of, until it finally
gives up and falls back to comparing by object address.

>  E.g., what are the semantics if __lt__(a,b) returns true the first
> time and false the second time?

This question didn't make sense, since the only __lt__ example you gave
returned NotImplemented in every case.  At a higher level, if you write
comparison methods that return inconsistent results, you may get back
inconsistent results -- but that shouldn't be surprising <wink>.  Write a
specific test case and observe what it does.

> ...
> I would appreciate it if you could cc responses to
> edloper at gradient.cis.upenn.edu ...

If that's what Edw88253 resolves to, you got it.





More information about the Python-list mailing list