[Python-Dev] Intricacies of calling __eq__

Kevin Modzelewski kmod at dropbox.com
Wed Mar 19 00:42:29 CET 2014


My 2 cents: it feels like a slippery slope to start guaranteeing the number
and ordering of calls to comparison functions -- for instance, doing that
for the sort() function would lock in the sort implementation.  It feels
like the number/ordering of the calls should be "implementation-defined" in
the same way that dict iteration order is, or comparisons between
incomparable types; I don't think all of CPython's behavior should be
guaranteed as part of the language semantics, and that this kind of change
wouldn't have to necessarily represent "changing the semantics" if the
semantics weren't considered guaranteed in the first place.  On the other
hand, even if it's theoretically not guaranteed that the sort() function
calls __lt__specifically, in practice it'd be a bad idea for an alternative
implementation to call __gt__ instead, so I guess there's some aspect of
judgment as to what parts should be allowed to be CPython-defined (though
my personal take is that this doesn't apply to this particular case).


On Tue, Mar 18, 2014 at 7:21 AM, Steven D'Aprano <steve at pearwood.info>wrote:

> On Tue, Mar 18, 2014 at 01:21:05PM +0200, Maciej Fijalkowski wrote:
>
> > note that this is specifically about dicts, where __eq__ will be
> > called undecided number of times anyway (depending on collisions in
> > hash/buckets which is implementation specific to start with)
>
> Exactly. Using a __eq__ method with side-effects is a good way to find
> out how many collisions your dict has :-)
>
> But specifically with your example,
>
>     if x in d:
>         return d[x]
>
> my sense of this is that it falls into the same conceptual area as the
> identity optimization for checking list or set containment: slightly
> unclean, but justified. Provided d is an actual built-in dict, and it
> hasn't been modified between one call and the next, I think it would be
> okay to optimize the second lookup d[x].
>
> A question: how far away will this optimization apply?
>
>     if x in d:
>         do_this()
>         do_that()
>         do_something_else()
>         spam = d[x]
>
> Assuming no modifications to d, will the second lookup still be
> optimized?
>
>
>
> --
> Steven
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> https://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe:
> https://mail.python.org/mailman/options/python-dev/kmod%40dropbox.com
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20140318/c645b449/attachment.html>


More information about the Python-Dev mailing list