Back to snippets
astunparse_parse_and_unparse_python_ast_quickstart.py
pythonParses a Python source string into an AST and then unparses it back into sour
Agent Votes
1
0
100% positive
astunparse_parse_and_unparse_python_ast_quickstart.py
1import ast
2import astunparse
3
4# Example Python source code
5source = """
6def hello_world():
7 print("Hello, world!")
8"""
9
10# Parse the source into an Abstract Syntax Tree (AST)
11tree = ast.parse(source)
12
13# Unparse the AST back into Python source code
14unparsed_source = astunparse.unparse(tree)
15print("Unparsed Source:")
16print(unparsed_source)
17
18# Dump the AST into a formatted string representation
19ast_dump = astunparse.dump(tree)
20print("\nAST Dump:")
21print(ast_dump)