AST Tools

0.1.8 · active · verified Fri Apr 17

ast-tools is a Python library providing a toolbox for working with and transforming Python Abstract Syntax Trees (ASTs). It offers utilities like `MutableAST` for in-place modifications and a `Visitor` for traversing ASTs, simplifying complex AST manipulations. The current version is 0.1.8, and its release cadence is infrequent, with the last release in June 2022.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates converting a Python function to a mutable AST, modifying a binary operation within it, and then executing the transformed AST as a new function. It highlights the use of `MutableAST` for in-place modifications and `function_to_ast` / `eval_ast` for conversion.

import ast
from ast_tools.mutable_ast import MutableAST
from ast_tools.common import function_to_ast, eval_ast

def add_func(a, b):
    c = a + b
    return c

# Convert a Python function to a mutable AST representation
m = MutableAST(add_func)

# Example transformation: change '+' to '-' in the binary operation
for node in m.body:
    if isinstance(node, ast.Assign):
        if isinstance(node.value, ast.BinOp) and isinstance(node.value.op, ast.Add):
            node.value.op = ast.Sub()
            break # Assuming only one assignment in this simple example

# Convert the modified AST back into a runnable function
sub_func = eval_ast(m.ast)

# Test the transformed function
result = sub_func(10, 5)
print(f"Original function output (if run directly): {add_func(10, 5)}")
print(f"Transformed function output: {result}") # Expected: 5

view raw JSON →