New submission from Michael McCoy <>:

Exception handling matches subtypes, not subclasses

# Example

    from abc import ABC
    class MyException(Exception, ABC):
    class OtherException(Exception):
        raise OtherException
    except MyException:
        print("Correct: Caught MyException")
    except Exception:
        print("Wrong: Caught something else")
    # "Wrong: Caught something else"

# Background and evidence of bug-ness

Issue 2534 [1] (10 years ago!) introduced the behavior, but only in the Python 
3 patch [2]. During code review, the correct function call was used [3], but 
the function's name got switched in the final python3 patch without any comment.

The current Python 2 code uses `PyObject_IsSubclass`, and produces the correct 
behavior in the example above (using `__metaclass__ = ABCMeta`, of course). 
This leads me to strongly suspect that this is a bug, not a feature. The note 
below regarding unittest for further evidence that this code has eight legs.

Given the ancient nature of this bug, it affects all versions of python3.


# Solution

Coming very soon in a PR on Github, but in short, we do the following:

  1. Switch `PyType_IsSubtype` to  `PyObject_IsSubclass`.
  2. Revert the changes made to remove “dead code” in The code was dead because the wrong 
function was used—the PR left only the bug.
  3. Add tests. Note that `unittest`’s `self.assertRaises` function uses 
`issubclass` and does not alert to this bug. (Different symptom, same cause.)

# Note

This bug has nothing to do with the `abc` package, beyond being a simple way to 
generate the error.


Gitub: mbmccoy

components: Interpreter Core
messages: 315241
nosy: Michael McCoy
priority: normal
severity: normal
status: open
title: Exception handling matches subtypes, not subclasses
versions: Python 3.4, Python 3.5, Python 3.6, Python 3.7, Python 3.8

Python tracker <>
Python-bugs-list mailing list

Reply via email to