The rap against "while True:" loops

Steven D'Aprano steve at
Sun Oct 18 11:07:41 CEST 2009

On Sat, 17 Oct 2009 23:37:51 -0700, Paul Rubin wrote:

> Steven D'Aprano <steve at> writes:
>> For the record, the four lines Paul implies are "confusing" are:
>> try:
>>     d[key] += value
>> except KeyError:
>>     d[key] = value
> Consider what happens if the computation of "key" or "value" itself
> raises KeyError.

How does using a defaultdict for d save you from that problem?

table = {101: 'x', 202: 'y'}
data = {'a': 1, 'b': 2}
d = collections.defaultdict(int)
d[table[303]] += data['c']

It may not be appropriate to turn table and data into defaultdicts -- 
there may not be a legitimate default you can use, and the key-lookup 
failure may be a fatal error. So defaultdict doesn't solve your problem.

If you need to distinguish between multiple expressions that could raise 
exceptions, you can't use a single try to wrap them all. If you need to 
make that distinction, then the following is no good:

    key = keytable[s]
    value = datatable[t]
    d[key] += value
except KeyError:
    print "An exception occurred somewhere"

But if you need to treat all three possible KeyErrors identically, then 
the above is a perfectly good solution.


More information about the Python-list mailing list