[Python-Dev] Intricacies of calling __eq__
Maciej Fijalkowski
fijall at gmail.com
Wed Mar 19 14:09:04 CET 2014
On Wed, Mar 19, 2014 at 2:42 PM, Antoine Pitrou <solipsis at pitrou.net> wrote:
> 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.
I would like to point out that instructing people does not really
work. Besides, other examples like this:
if d[x] >= 3:
d[x] += 1 don't really work.
More information about the Python-Dev
mailing list