What errors does my Python module define and raise?

On StackOverflow someone asked a whileago whether you can find out what errors a module defines and throws.In Python, a function does not declare that it throws a particularerror object, so you need to look inside the module to see whatexceptions it defines, or what exception it raises. You can do this byreading the docs (RTFM!) but of course they may be out of date, orwhat have you, so an alternative is to use the Python API to do lookfor you.

Which errors does a module define?

To first find which exceptions a module defines, just write a simplescript to go through each object in the module dictionarymodule.__dict__ and see if it ends in the word Error or if it is asubclass of Exception:


If I run this on the shutils module from the standard library I get this:


$ python listexn.py shutil
Looking for exception types in module: shutil
shutil.Error is an exception type
shutil.WindowsError is an exception type

That tells you which errors are defined, but not which ones are thrown. Of course, if the module has errors with funny names, or ones that are not subclasses of Exception, then this code will miss them.

What errors are thrown by a module?

To find out what errors a module can throw, we need to walk over theabstract syntax tree generated when the Python interpreter parses themodule, and look for every raise statement, then save a list of nameswhich are raised. The code for this is a little long, but pretty straightforward, so first I’ll state the output:

$ python listexn-raised.py /usr/lib/python2.6/shutil.py

Looking for exception types in: /usr/lib/python2.6/shutil.py/usr/lib/python2.6/shutil.py:

OSError is an exception type

/usr/lib/python2.6/shutil.py:Error is an exception type


So now we know that shutil.py defines the errors Error andWindowsError and raises the exception OSError and Error. If wewant to be a bit more complete, we could write another method to checkevery except clause to also see which exceptions shutil handles.

Here’s the code to walk over the AST, it just uses thecompiler.visitor interface to create a walker which implements thevisitor pattern from the Gang of Four book:

#!/usr/bin/env python
import compiler.ast
import compiler.visitor as visitor
__author__ = 'Sarah Mount <s.mount@wlv.ac.uk>'
__date__ = 'May 2010'
class ExceptionFinder(visitor.ASTVisitor):
"""List all exceptions raised by a module.
def __init__(self, filename):
self.filename = filename
self.exns = set()
def __visitName(self, node):
"""Should not be called by generic visit, otherwise every name
will be reported as an exception type.
def __visitCallFunc(self, node):
"""Should not be called by generic visit, otherwise every name
will be reported as an exception type.
def visitRaise(self, node):
"""Visit a raise statement.
Cheat the default dispatcher.
if isinstance(node.expr1, compiler.ast.Name):
elif isinstance(node.expr1, compiler.ast.CallFunc):
if __name__ == '__main__':
import sys
if len(sys.argv) <= 1:
print 'Give me a file name!'
print 'Looking for exception types in: %s' % sys.argv[1]
lint = ExceptionFinder(sys.argv[1])
for exn in lint.exns:
print '%s:%s is an exception type' % (sys.argv[1], exn)

view raw
hosted with ❤ by GitHub

This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

2 Responses to What errors does my Python module define and raise?

  1. Anonymous says:


  2. Anonymous says:

    Great solution !

Please leave a response

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s