Skip to content

Instantly share code, notes, and snippets.

@snim2
Created May 16, 2010 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snim2/402869 to your computer and use it in GitHub Desktop.
Save snim2/402869 to your computer and use it in GitHub Desktop.
Find exception names in a Python module
#!/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):
visitor.ASTVisitor.__init__(self)
self.filename = filename
self.exns = set()
return
def __visitName(self, node):
"""Should not be called by generic visit, otherwise every name
will be reported as an exception type.
"""
self.exns.add(node.name)
return
def __visitCallFunc(self, node):
"""Should not be called by generic visit, otherwise every name
will be reported as an exception type.
"""
self.__visitName(node.node)
return
def visitRaise(self, node):
"""Visit a raise statement.
Cheat the default dispatcher.
"""
if isinstance(node.expr1, compiler.ast.Name):
self.__visitName(node.expr1)
elif isinstance(node.expr1, compiler.ast.CallFunc):
self.__visitCallFunc(node.expr1)
return
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])
compiler.walk(compiler.parseFile(sys.argv[1]),
lint,
walker=lint,
verbose=5)
for exn in lint.exns:
print '%s:%s is an exception type' % (sys.argv[1], exn)
@snim2
Copy link
Author

snim2 commented Jul 30, 2022 via email

@shadycuz
Copy link

shadycuz commented Oct 4, 2022

@snim2 The initial release of Deep-AST is out. Thanks for the inspiration, I will make sure I add this gist to the README.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment