[Python-Dev] Intricacies of calling eq (original) (raw)

Steven D'Aprano steve at pearwood.info
Tue Mar 18 15:21:16 CET 2014


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



More information about the Python-Dev mailing list