[Python-Dev] Intricacies of calling __eq__

Antoine Pitrou solipsis at pitrou.net
Wed Mar 19 13:42:28 CET 2014


On Tue, 18 Mar 2014 09:52:05 +0200
Maciej Fijalkowski <fijall at gmail.com> wrote:
> 
> We're thinking about doing an optimization where say:
> 
> if x in d:
>    return d[x]
> 
> where d is a dict would result in only one dict lookup (the second one
> being constant folded away). The question is whether it's ok to do it,
> despite the fact that it changes the semantics on how many times
> __eq__ is called on x.

I don't think it's ok. If the author of the code had wanted only one
lookup, they would have written:

  try:
      return d[x]
  except KeyError:
      pass

I agree that an __eq__ method with side effects is rather bad, of
course.
What you could do is instruct people that the latter idiom (EAFP)
performs better on PyPy.

Regards

Antoine.




More information about the Python-Dev mailing list