Created
August 24, 2017 20:29
-
-
Save calebmadrigal/0ea93a58cfc7f9d91613aab30d33e20f to your computer and use it in GitHub Desktop.
Example of changing the python AST
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
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