Skip to content

Instantly share code, notes, and snippets.

@calebmadrigal
Created August 24, 2017 20:29
Show Gist options
  • Save calebmadrigal/0ea93a58cfc7f9d91613aab30d33e20f to your computer and use it in GitHub Desktop.
Save calebmadrigal/0ea93a58cfc7f9d91613aab30d33e20f to your computer and use it in GitHub Desktop.
Example of changing the python AST
import ast
class StringWrapper(ast.NodeTransformer):
"""Wraps all strings in 'START ' + string + ' END'. """
def visit_Str(self, node):
return ast.Call(func=ast.Name(id='wrap_string', ctx=ast.Load()),
args=[node], keywords=[])
def wrap_string(s):
return 'START ' + s + ' END'
code = "print('test string')"
print(code)
print()
print("Without AST transformation:")
exec(code)
print()
print("With AST transformation:")
tree = ast.parse(code)
tree = StringWrapper().visit(tree)
# Add lineno & col_offset to the nodes we created
ast.fix_missing_locations(tree)
co = compile(tree, "<ast>", "exec")
exec(co)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment