[New-bugs-announce] [issue25537] Call `isinstance` instead of `issubclass` during exception handling

Sjoerd Job Postmus report at bugs.python.org
Mon Nov 2 16:10:26 EST 2015


New submission from Sjoerd Job Postmus:

Currently Python2.7 calls `PyObject_IsSubclass` during exception handling. This allows some virtual-base-class machinery to make Python believe a certain class should match an exception while it in reality does not.

However, this does not necessarily give one really enough granularity when dealing with base libraries which are not as granular in raising exceptions as one would like (the Python base library before PEP3151 comes to mind).

Currently I used the trick of calling `isinstance(sys.exc_info()[1], cls)` in the `__subclasscheck__`, which is sort-of a great work-around.[*].

This method is great for sort-of emulating PEP3151 in Python2.7, and similar work can be done for other libraries: making the exception classes appear more granular based on properties of the instance of the exception.

My belief is that by calling the `isinstance` during exception handling, one can use virtual base classes (or should I say virtual base instances) to their fullest potential in writing cleaner code.

I think this is important because exception-handling is already a place where messy code is likely to occur, and we need all the support we can get in making it just a tad less messy.[**]

Note: Python3.5 calls `PyType_IsSubtype`, which has #12029 open for a change towards `PyObject_IsSubclass`. As soon as (or before) that's implemented, I'd like to propose a similar change for Python3.5+: call `PyObject_IsInstance` when the raised exception is an instance.

[*] See https://github.com/sjoerdjob/exhacktion/ for how I use the described hack to somewhat emulate PEP3151 in Python2.7.
[**] One question that comes to mind is: why not just write a wrapper around the offending library. (1): If it's the base library, almost nobody is going to bother. (2): even if it's not the base library, the wrapper will likely be even more function calls, which may cost performance in both the good and the bad cases, instead of just the bad cases.

----------
components: Interpreter Core
messages: 253946
nosy: sjoerdjob
priority: normal
severity: normal
status: open
title: Call `isinstance` instead of `issubclass` during exception handling
type: enhancement
versions: Python 2.7, Python 3.5, Python 3.6

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue25537>
_______________________________________


More information about the New-bugs-announce mailing list