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

Chris Angelico rosuav at gmail.com
Thu Nov 5 03:21:17 EST 2015


On Thu, Nov 5, 2015 at 7:05 PM, Serhiy Storchaka <storchaka at gmail.com> wrote:
> On 05.11.15 00:02, sjoerdjob at sjec.nl wrote:
>>
>> Now, PEP3151 took over a year to be resolved, judging by the dates. If
>> we have to go through changes like this more often, one will have to
>> wait quite a while. Also, consider backwards compatibility issues. Code
>> using FileNotFoundError will only run on Python3.3+.
>>
>> Thus I propose to have the exception handling code use the normal
>> `isinstance` machinery, as it is more powerful, and allows one to use
>> virtual base classes to check if the instance of the exception is
>> relevant to catch. An example:
>>
>>      import errno
>>
>>      # Fake `FileNotFoundError` in Python3.2
>
>
> Do you propose to add a new feature in 3.2?

I think the point is to future-proof Python against further such
incidents, and to allow some measure of control even over third-party
libraries. For instance, psycopg2 dumps ProgrammingError on you for
lots of all SQL errors, but has a few special cases like
IntegrityError; if there's some special case that isn't handled by
psycopg2 itself, you have no recourse but to catch something too broad
and then manually filter.

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. Also, what happens if you have
a bug in your __instancecheck__ method? It's going to be *extremely*
hard to track down. How often does this sort of except-level
specialization come up?

ChrisA


More information about the Python-ideas mailing list