RedBaron

0.9.2 · maintenance · verified Tue Apr 14

RedBaron is a Python library built on top of Baron, providing a higher-level abstraction for working with Python source code as a Full Syntax Tree (FST). It aims to simplify tasks like refactoring, code analysis, and programmatic code modification while preserving all syntax information, including comments and formatting. The library is currently at version 0.9.2, with its last release in March 2019, indicating a maintenance or slow development cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse Python code into a RedBaron FST, find a function, modify its name and a variable's value within it, add a new line, and then convert the modified FST back into a Python string. RedBaron's API is designed to be intuitive for tree traversal and modification.

from redbaron import RedBaron

code = """
def my_function(arg1, arg2):
    value = 42
    print(f"Hello {value}")
"""

red = RedBaron(code)

# Find the function definition by name
func_node = red.find("def", name="my_function")

# Change the function name
func_node.name.value = "my_renamed_function"

# Find the variable assignment and change its value
value_assignment_node = func_node.find("assignment", target="value")
if value_assignment_node:
    value_assignment_node.value.value = "99"

# Add a new line (comment) at the end of the function body
# Note: Raw strings might be needed for complex insertions
func_node.value.append("    # Added by RedBaron\n")

# Dump the modified code back to a string
print(red.dumps())

view raw JSON →