Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# sample of ast module
# reference:
# http://docs.python.jp/2.7/library/ast.html
# http://stackoverflow.com/questions/1515357/simple-example-of-how-to-use-ast-nodevisitor
import ast
import sys
import logging
class SampleVisitor(ast.NodeVisitor):
def generic_visit(self, node):
print("type of node: {0}".format(type(node).__name__))
ast.NodeVisitor.generic_visit(self, node)
def visit_Load(self, node):
pass
def visit_Name(self, node):
print("Name: {0}".format(node.id))
def visit_Num(self, node):
print("Num: {0}".format(node.n))
if len(sys.argv) != 2:
logging.error("usage: ast_example.py [word]")
sys.exit(1)
expr = sys.argv[1]
print("expression: {0}".format(expr))
tree = ast.parse(expr)
sv = SampleVisitor()
sv.visit(tree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.