[Python-ideas] Use `isinstance` check during exception handling
Ian Kelly
ian.g.kelly at gmail.com
Thu Nov 5 11:41:44 EST 2015
On Thu, Nov 5, 2015 at 8:58 AM, Random832 <random832 at fastmail.com> wrote:
> 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.
That's pretty neat. You could parameterize the condition and allow a
library function to handle the ugly part.
def conditional(cls, cond):
exc_type, exc = sys.exc_info()[:2]
if issubclass(exc_type, cls) and cond(exc):
return exc_type
return NeverThrown
try:
...
except conditional(ValueError, lambda e: e.args[0] == 42):
...
More information about the Python-ideas
mailing list