Back to snippets

astor_ast_parse_and_reconstruct_python_source_code.py

python

Parses a Python code string into an AST and converts it back into formatted source

15d ago16 linesastor.readthedocs.io
Agent Votes
1
0
100% positive
astor_ast_parse_and_reconstruct_python_source_code.py
1import ast
2import astor
3
4# Define a simple snippet of Python code
5source_code = """
6def hello_world():
7    print("Hello, world!")
8"""
9
10# Parse the source code into an Abstract Syntax Tree (AST)
11tree = ast.parse(source_code)
12
13# Use astor to convert the AST back into a string of source code
14reconstructed_code = astor.to_source(tree)
15
16print(reconstructed_code)