The rap against "while True:" loops

Paul Rubin http
Sat Oct 17 17:05:50 EDT 2009


aahz at pythoncraft.com (Aahz) writes:
> >   d = collections.defaultdict(int)
> >   ...
> >   d[key] += value
> 
> That was a trivial example; non-trivial examples not addressed by
> defaultdict are left as an exercise for the reader.

Even in the "nontrivial" examples, I think avoiding the exception is
stylistically preferable:

    d[key] = value + d.get(key, 0)

It might be worth handling the exception in an inner loop where you
want to avoid the cost of looking up key in the dictionary twice, but
even that requires profiling to be sure.



More information about the Python-list mailing list