Search code examples
pythonequalityequivalence

User-defind type with built-in type comparison


I'm writing a context manager allowing to catch a certain type of exception.

class AssertRaises(object):
    def __init__(self, exc_type):
        self.exc_type = exc_type

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type == self.exc_type:
            raise AssertionError
        return True

This manager works fine when built-in exception raises but fails with such usage:

class MyTypeError(TypeError):
    pass


try:
    with AssertRaises(TypeError):
        raise MyTypeError()
except Exception as e:
    print(type(e).__name__)

In this example the user-defined excepton raises, but this exception is equivalent to TypeError and I want it to be processed by context manager as TypeError. I checked that `isinstance(MyTypeError(), TypeError) == True' and want

__exit__(...)

to work in the same way (to consider inheritance). Is there any solution?


Solution

  • Either check the exception itself (exc_val) as you've done with isinstance(), or use issubclass():

    def __exit__(self, exc_type, exc_val, exc_tb):
        if issubclass(exc_type, self.exc_type):
            raise AssertionError
        return True