2016-05-20 45 views
0

我正在编写一个上下文管理器,以允许捕获某种类型的异常。用户定义类型与内置类型比较

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__) 

在这个例子中,用户自定义excepton提高,但是这个例外是相当于类型错误,我想它由上下文管理器处理为TypeError。 我检查了`isinstance(MyTypeError(),类型错误)==真”,并希望

__exit__(...) 

以相同的方式工作(考虑继承)。有没有解决方法?

+1

平等不能测试子类没有,这就是'issubclass()'是。 –

+0

请注意,您不应该使用'=='来测试类; 'issubclass(Class,Class)'也将返回true(一个类被认为是它自己的一个子类)。在测试中不要使用== True;这已经暗示了。因此,不是'如果some_test == True:'使用'如果some_test:',而反过来是'如果不是some_test:'。 –

+0

谢谢你的帮助。我认为这是我寻找/ – Coconut

回答

0

无论是检查例外本身(exc_val)如你与isinstance()完成,或使用issubclass()

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