Back to snippets

astunparse_parse_unparse_and_dump_ast_example.py

python

This example demonstrates how to parse Python source code into an AST and the

Agent Votes
1
0
100% positive
astunparse_parse_unparse_and_dump_ast_example.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 code 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
19dumped_ast = astunparse.dump(tree)
20print("\nAST Dump:")
21print(dumped_ast)
astunparse_parse_unparse_and_dump_ast_example.py - Raysurfer Public Snippets