[Python-ideas] suppressing exception context when it is not relevant

Nick Coghlan ncoghlan at gmail.com
Tue Oct 11 00:49:28 EDT 2016


On 11 October 2016 at 10:43, Václav Dvořák <vashek at gmail.com> wrote:
> But I find this misleading, as the original KeyError is not really an error
> at all. I could of course avoid the situation by changing the try/except
> (EAFP) into a test for the key's presence (LBYL) but that's not very
> Pythonic and less thread-friendly (not that the above is thread-safe as is,
> but that's beside the point). Also, yes, I could instead subclass dict and
> implement __missing__, but that's only a solution for this particular case.
> The problem (if you agree it's a problem) occurs any time an exception is
> not actually an error, but rather a condition that just happens to be
> indicated by an exception.
>
> It's unreasonable to expect all code in some_api to change their raise X to
> raise X from None (and it wouldn't even make sense in all cases). Is there a
> clean solution to avoid the unwanted exception chain in the error message?

Yes, you can restructure the code so you're not doing further work in
the exception handler, and instead do the work after the try/except
block finishes and the exception context is cleared automatically:

    value = MISSING = object()
    try:
        value = cache_dict[key]
    except KeyError:
        pass
    if value is MISSING:
        value = some_api.get_the_value_via_web_service_call(key)
        cache_dict[key] = value

(This is the general case of MRAB's answer, as the try/except
KeyError/pass pattern above is what dict.get() implements)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list