具有内置类型比较的用户定义类型

User-defind type with built-in type comparison

我正在编写一个允许捕获特定类型异常的上下文管理器。

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

此管理器在引发内置异常时工作正常但因此类用法而失败:

class MyTypeError(TypeError):
    pass


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

在此示例中,引发了用户定义的异常,但此异常等同于 TypeError,我希望上下文管理器将其作为 TypeError 进行处理。 我检查了 `isinstance(MyTypeError(), TypeError) == True' 并想要

__exit__(...)

以同样的方式工作(考虑继承)。有什么解决办法吗?

要么检查异常本身 (exc_val),就像您对 isinstance() 所做的那样,或者使用 issubclass():

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