The rap against "while True:" loops

Iain King iainking at gmail.com
Tue Oct 20 11:42:16 CEST 2009


On Oct 19, 7:51 am, Hendrik van Rooyen <hend... at microcorp.co.za>
wrote:
> On Sunday, 18 October 2009 11:31:19 Paul Rubin wrote:
>
> > Hendrik van Rooyen <hend... at microcorp.co.za> writes:
> > > Standard Python idiom:
>
> > > if key in d:
> > >   d[key] += value
> > > else:
> > >   d[key] = value
>
> > The issue is that uses two lookups.  If that's ok, the more usual idiom is:
>
> >   d[key] = value + d.get(key, 0)
>
> I was actually just needling Aahz a bit.  The point I was trying to make
> subliminally, was that there is a relative cost of double lookup for all
> cases versus exceptions for some cases. - Depending on the frequency
> of "some", I would expect a breakeven point.
>
> - Hendrik

Indeed - the method I use for this (picked up from this newsgroup), is
to work out roughly how often you need to make a new record instead of
altering a current one, and depending on that use either:

if key in d:
    d[key] += value
else:
    d[key] = value

or

try:
    d[key] += value
except KeyError:
    d[key] = value


I find both to be easily readable (and the similarity between the two
blocks is obvious and, to me at least, pleasing).

Iain



More information about the Python-list mailing list