# Expose PyErr\_GivenExceptionMatches in inspect

**URL:** <https://discuss.python.org/t/expose-pyerr-givenexceptionmatches-in-inspect/17420>\
**Category:** Ideas\
**Created:** [July 16, 2022, 9:48am UTC](https://discuss.python.org/t/expose-pyerr-givenexceptionmatches-in-inspect/17420 "2022-07-16T09:48:14Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![graingert](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/graingert/32/26847_2.png) [@graingert](https://discuss.python.org/u/graingert)\
**Post date:** [July 16, 2022, 9:48am UTC](https://discuss.python.org/t/expose-pyerr-givenexceptionmatches-in-inspect/17420/1 "2022-07-16T09:48:14Z")

</div>

the try/except exception matching is now documented such that “except does not match virtual subclasses of the specified exception type”

see [[doc] clarify that except does not match virtual subclasses of the specified exception type · Issue #56238 · python/cpython · GitHub](https://github.com/python/cpython/issues/56238)

I’d like to be able to emulate this behaviour in a few places, such as implementing context managers with `def __exit__ (` eg:

```auto
class ExampleContextManager:
    def __enter__ (self):
        return self

    def __exit__ (self, typ, value, traceback):
        if typ is None:
            return False

        if value is None:
            value = typ()

        if inspect.exceptionmatches(exc, SomeType):
            # handle SomeType case

```

So I’m proposing a python implementation of PyErr\_GivenExceptionMatches be made available as `inspect.exceptionmatches`

---

<div class="post-metadata">

**Author:** ![iritkatriel](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/iritkatriel/32/2615_2.png) [@iritkatriel](https://discuss.python.org/u/iritkatriel)\
**Post date:** [July 16, 2022, 10:07am UTC](https://discuss.python.org/t/expose-pyerr-givenexceptionmatches-in-inspect/17420/2 "2022-07-16T10:07:26Z")

</div>

Since PyErr\_GivenExceptionMatches is part of the public c api, I don’t see any reason not to expose it in python.

---

<div class="post-metadata">

**Author:** ![TeamSpen210](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/teamspen210/32/1004_2.png) [@TeamSpen210](https://discuss.python.org/u/TeamSpen210)\
**Post date:** [July 16, 2022, 10:03pm UTC](https://discuss.python.org/t/expose-pyerr-givenexceptionmatches-in-inspect/17420/3 "2022-07-16T22:03:34Z")

</div>

Perhaps it should go in `operator`, since that’s where function versions of other fundamental operations are exposed. Though it’s obviously very inefficient, here’s a method for a pure-Python implementation:

```nohighlight
def exception_matches(exc, expected):
    traceback = exc. __traceback__
    context = exc. __context__
    cause = exc. __cause__
    suppress = exc. __suppress_context__
    try:
        try:
            raise exc
        except expected:
            return True
        except:
            return False
    finally:
        exc. __traceback__ = traceback
        exc. __context__ = context
        exc. __cause__ = cause
        exc. __suppress_context__ = suppress

```

---

<div class="post-metadata">

**Author:** ![steven.daprano](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/steven.daprano/32/1083_2.png) [@steven.daprano](https://discuss.python.org/u/steven.daprano)\
**Post date:** [July 17, 2022, 2:22am UTC](https://discuss.python.org/t/expose-pyerr-givenexceptionmatches-in-inspect/17420/4 "2022-07-17T02:22:25Z")

</div>

Wouldn’t a simpler Python implementation just duplicate the high-level exception matching logic?

```python
def exception_matches(exc, expected):
    """Return whether or not "raise exc" will be caught by "except expected"."""
    if isinstance(exc, type):
        return isubclass(exc, expected)
    return isinstance(exc, excepted)

```

Have I missed any cases, or some other issue?

It would be nice to have an official way to do this. The operator module makes sense to me.

---

<div class="post-metadata">

**Author:** ![TeamSpen210](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/teamspen210/32/1004_2.png) [@TeamSpen210](https://discuss.python.org/u/TeamSpen210)\
**Post date:** [July 17, 2022, 3:22am UTC](https://discuss.python.org/t/expose-pyerr-givenexceptionmatches-in-inspect/17420/5 "2022-07-17T03:22:39Z")

</div>

Unlike regular instance checks, exception handling skips all of the various hooks - the `abc` modules, ` __class__ `, ` __instancecheck__ ()` and ` __subclasscheck__ ()`, etc. Examining the implementation of `PyErr_GivenExceptionMatches()` though suggests perhaps a better function to expose `PyType_IsSubtype()`, since the `PyErr_GivenExceptionMatches()` just recursively handles tuples and verifies they are exceptions.
