volingas
volingas

Reputation: 1173

How to check if class is exception class?

I define a custom exception:

>>> class MyException(Exception):
>>>     pass

I create an exception instance:

>>> a = MyException()

I check if this is an exception. As expected, it is:

>>> isinstance(a, Exception)
True 

But how do I check if the class is an exception class?

>>> myclass = MyException
>>> isinstance(myclass, Exception)
False

Upvotes: 6

Views: 2150

Answers (2)

fixatd
fixatd

Reputation: 1404

You can try checking if Exception is under __bases__:

>>> my_class = MyException
>>> Exception in my_class.__bases__
True

Upvotes: 0

Chetan Ameta
Chetan Ameta

Reputation: 7896

you can check if one class is inherited from other class by using issubclass function

print issubclass(MyException, Exception)

result:

True

Upvotes: 8

Related Questions