Skip to content

Instantly share code, notes, and snippets.

@dcolish
Created January 7, 2011 15:23
Show Gist options
  • Save dcolish/769584 to your computer and use it in GitHub Desktop.
Save dcolish/769584 to your computer and use it in GitHub Desktop.
Check a Python AST for a few issues I'd like to avoid
from ast import Name, NodeTransformer, parse, Return
from itertools import chain
import sys
from warnings import warn
class StaticTransformer(NodeTransformer):
def _check_none(self, x):
if isinstance(x, Name) and x.id == 'None':
warn("Passing None Argument to function", RuntimeWarning)
def visit_FunctionDef(self, node):
self.generic_visit(node)
if not all([isinstance(x, Return) for x in node.body]):
warn("Returning None from function %s" % node.name, RuntimeWarning)
return node
def visit_Call(self, node):
self.generic_visit(node)
for x in chain(node.args, node.keywords):
x = x.value if hasattr(x, 'value') else x
self._check_none(x)
return node
with open(sys.argv[1]) as f:
source = f.read()
ast = parse(source, sys.argv[1])
node = StaticTransformer().visit(ast)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment