[Python-ideas] Use `isinstance` check during exception handling

Random832 random832 at fastmail.com
Thu Nov 5 10:58:55 EST 2015


Chris Angelico <rosuav at gmail.com> writes:
> I do like the idea of being able to refactor exception specialization code:
>
> try:
>     ...
> except BroadError as e:
>     if is_narrower_error(e):
>         # handle NarrowerError
>     else:
>         raise
>
> but I don't know whether it's worth complicating the core exception
> handling system with such a rare case.

The syntax could be this:
except BroadError as e if is_narrower_error(e):

I think the bytecode *already* evaluates a boolean expression
which today happens to always be a comparison of the exception's
type. Notably, the exception type itself can apparently be an
arbitrary expression, which (I was mildly surprised to discover)
has access to sys.exc_info.

class NeverThrown(Exception): pass

def exfilter():
   etype, e = sys.exc_info()[:2]
   if is_narrower_error(e): return etype
   else: return NeverThrown

try:
   ...
except exfilter() as e:
   ...

This is, of course, a *profoundly* ugly way to do this.



More information about the Python-ideas mailing list