Created
May 16, 2010 13:08
-
-
Save snim2/402869 to your computer and use it in GitHub Desktop.
Find exception names in a Python module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@snim2 The initial release of Deep-AST is out. Thanks for the inspiration, I will make sure I add this gist to the README.