ASTOR: Read/rewrite/write Python ASTs

0.8.1 · maintenance · verified Sun Apr 05

astor is a Python library designed for easy manipulation of Python source code via its Abstract Syntax Tree (AST). It provides functionality to round-trip an AST back to Python source, pretty-print ASTs for debugging, and offers both recursive and non-recursive tree traversal mechanisms. It focuses on generating readable code from modified ASTs. The current version is 0.8.1, released in late 2019, and its release cadence is very slow, indicating a maintenance-only status.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse a Python source code string into an Abstract Syntax Tree (AST) using Python's built-in `ast` module, and then convert it back into formatted Python source code using `astor.to_source`.

import ast
import astor

# Example Python code as a string
source_code = """
def greet(name):
    message = f"Hello, {name}!"
    return message
"""

# Parse the source code into an AST
tree = ast.parse(source_code)

# Convert the AST back to source code
generated_source = astor.to_source(tree)

print("Original code:\n" + source_code)
print("\nGenerated code from AST:\n" + generated_source)

view raw JSON →