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

Sjoerd Job Postmus sjoerdjob at sjec.nl
Thu Nov 5 11:53:24 EST 2015


This does sound like a nice approach. Neat! 

However: it *does* depend on only being resolved during the exception being matched. So you can't pre-define it.

Still, I like it. 

> On 5 Nov 2015, at 17:41, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> 
>> 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):
>    ...
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/


More information about the Python-ideas mailing list