[Python-Dev] An interesting exception handling quirk

Nick Coghlan ncoghlan at gmail.com
Sun Oct 20 12:24:25 CEST 2013


On 20 October 2013 16:08, Armin Rigo <arigo at tunes.org> wrote:
> Hi Nick,
>
> On Sat, Oct 19, 2013 at 1:41 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> recreating the *exact* exception subclass check from
>> Python is actually difficult these days.
>
> Can't it be done roughly like that?
>
>    def __exit__(self, typ, val, tb):
>         try:
>             raise typ, val
>         except self.exceptions:
>             return True
>         except:
>             return False

In Python 3, you have to use "raise type if val is None else val"
instead, and you then have to deal with the fact that raise will
overwrite an already set __context__ on the exception value
(contextlib.ExitStack actually has to work around that when unwinding
the stack by restoring a more appropriate __context__ value). But yes,
actually reraising it does let you reproduce the exception matching.

That said, it actually occurs to me now that the current behaviour
(overwriting an already set __context__) could arguably be considered
a bug, since we don't overwrite an already set __traceback__.

Cheers,
Nick.

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


More information about the Python-Dev mailing list