__lt__ slowing the "in" operator even if not called

Christophe chris.cavalaria at free.fr
Thu Jun 15 08:54:58 EDT 2006


Emanuele Aina a écrit :
> Maric Michaud continuò:
> 
> 
>>>But I hoped in a more exaustive answer: why python has to do this
>>>lookup when the __lt__ method is not involved at all?
>>
>>It is not the case, that's what my program shows :
>>
>><class '__main__.StateEQ'>
>>
>>in operator at the beginning of list: 173
>>in operator at the end of list: 28249 <- here
>>
>>converting to dict : 79
>>in operator for a dict for 60000 elements: 14
>>
>><class '__main__.StateLTEQ'>
>>
>>in operator at the beginning of list: 202
>>in operator at the end of list: 30472 <- and here
> 
> 
> It is very obvious that these two have similiar timings, as both call
> __eq__.
> 
> I asked why the State and StateLT don't give similar results, but
> StateLT is noticeably slower.
> 

Maybe because when python tries to compare 2 elements, checks if __lt__ 
is defined, and if it is, it checks for __gt__ ( or maybe __lteq__ ) but 
since it isn't defined, it fallbacks on __cmp__. So for each comparison, 
if you define only __lt__ you have some additional lookups to go through.



More information about the Python-list mailing list