6

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

2 Answers 2

8

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

print issubclass(MyException, Exception)

result:

True
Sign up to request clarification or add additional context in comments.

1 Comment

Cool. I need it to distinguish between object instances and sub-classes of Exception (for unit testing), and unfortunately issubclass fails for non-class objects.
0

You can try checking if Exception is under __bases__:

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

1 Comment

Thanks, a bit hacky

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.