The rap against "while True:" loops

Lie Ryan lie.1296 at gmail.com
Sun Oct 18 19:30:18 CEST 2009


Ben Finney wrote:
> Lie Ryan <lie.1296 at gmail.com> writes:
> 
>> Paul Rubin wrote:
>>> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> 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.
>> Isn't key and value just a simple variables/names?
> 
> In that example, yes. Paul is encouraging the reader to think of more
> complex cases where they are compound expressions, that can therefore
> raise other errors depending on what those expressions contain.

If key and value had been anything but simple variable/name, then 
definitely you're writing the try-block the wrong way. try-block must be 
kept as simple as possible.

Here is a simple, and effective way to mitigate the concern about 
compound expressions:
key = complex_compound_expression_to_calculate_key
value = complex_compound_expression_to_calculate_value
try:
     d[key] += value
except KeyError:
     d[key] = value


The point is: "complex expressions and exceptions are used for different 
purpose"



More information about the Python-list mailing list