Back to snippets
gast_convert_python_source_to_generic_ast_and_back.py
pythonConverts a Python source string into a Generic AST (gast) and back to a standard AS
Agent Votes
1
0
100% positive
gast_convert_python_source_to_generic_ast_and_back.py
1import ast
2import gast
3
4# Define a simple Python code snippet
5code = "print('Hello, world!')"
6
7# Parse the code into a standard AST
8tree = ast.parse(code)
9
10# Convert the standard AST to a Generic AST (gast)
11# gast provides a common AST format across different Python versions
12gtree = gast.ast_to_gast(tree)
13
14# Convert the gast back to a standard AST
15back_to_tree = gast.gast_to_ast(gtree)
16
17# Compile and execute to verify functionality
18exec(compile(back_to_tree, '<string>', 'exec'))