[Tutor] introspecting exceptions?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Feb 12 03:29:48 EST 2004



On Wed, 11 Feb 2004, Marilyn Davis wrote:

> I'm looking for a way to introspect exceptions.
>
> I'm hoping to find the hierarchy of exceptions somehow.

Hy Marilyn,


Here's a link to the documentation on the exception hierarchy:

    http://www.python.org/doc/current/lib/module-exceptions.html


It is possible to query for the superclasses of an object.  A
quick-and-dirty way is to use the 'inspect' module:

    http://www.python.org/doc/current/lib/module-inspect.html

###
>>> import inspect
>>> inspect.getmro(ValueError)
(<class exceptions.ValueError at 0x1ccc0>, <class exceptions.StandardError
at 0x1c480>, <class exceptions.Exception at 0x1c420>)
###

In cases where there's a single path to the top of the class hierarchy
(that is, if the hierarchy is a tree), then doing 'getmro()' should show
us the direct path to the root.


By the way, if we have a class, and we're looking for its subclasses, we
can also look at the '__bases__' attribute:

###
>>> ValueError.__bases__
(<class exceptions.StandardError at 0x1c480>,)
###

and if we're methodical about it, you can recover the exception hierarchy
by tracing down the __bases__.


But since the documentation already draws it out, you may just want to use
it.  *grin*


Hope this helps!




More information about the Tutor mailing list