[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Wed Feb 19 02:00:02 CET 2014


On Wed, Feb 19, 2014 at 11:10 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>         for key in sequence:
>             x = (d1[key] except KeyError: (d2[key] except KeyError: 0))
>
> Take the colons and brackets out, and I think it is less readable:
>
>             x = d1[key] except KeyError d2[key] except KeyError 0
>
> and ambiguous.
>
> By the way, I think this is a good example for the PEP (Chris are you
> reading?). You might be tempted to re-write this as:
>
>             x = d1.get(key, d2.get(key, 0))
>
> which is shorter, but the semantics are different. If the second case,
> you have to pre-calculate the fallback, which may be expensive, while in
> the exception form, you only calculate the fallback if the first lookup
> actually fails.

I certainly am reading :) Going a bit further by having the final
fall-back be a function call (highlighting the fact that it may be
expensive).

"""
Consider this example of a two-level cache::
    for key in sequence:
        x = (lvl1[key] except KeyError: (lvl2[key] except KeyError: f(key)))

This cannot be rewritten as::
        x = lvl1.get(key, lvl2.get(key, f(key)))

which, despite being shorter, defeats the purpose of the cache, as it must
calculate a default value to pass to get(). The .get() version calculates
backwards; the exception-testing version calculates forwards, as would be
expected.
"""

ChrisA


More information about the Python-ideas mailing list