Ben Finney wrote:
Lie Ryan <lie.1...@gmail.com> writes:

Paul Rubin wrote:
Steven D'Aprano <st...@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"
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to