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

Sjoerd Job Postmus sjoerdjob at sjec.nl
Thu Nov 5 11:08:51 EST 2015


Yes. This way is really ugly.

Also, wrt to the `if` statement: that only works nicely if you don't really want support for the tuple-case. How would you model different conditions for different elements of the tuple?

> On 5 Nov 2015, at 16:58, Random832 <random832 at fastmail.com> wrote:
> 
> 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.
> 
> _______________________________________________
> 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