RedBaron
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
- breaking In version 0.9, the internal structure for annotations changed. Annotations are now members of `DefArgument`, `ListArgument`, and `DictArgument` nodes, and the `TypedNameNode` has been removed. Code directly accessing `TypedNameNode` or expecting the old annotation structure will break.
- breaking In version 0.6, `IntNode.value` changed from returning an `int` to a `string`. Use `IntNode.to_python()` for an evaluated integer. Additionally, the `node.find("name")` shortcut now *only* works with possible node identifiers, raising `AttributeError` otherwise.
- gotcha RedBaron operates on a Full Syntax Tree (FST) provided by Baron, which is a lossless representation of the source code. Unlike a traditional Abstract Syntax Tree (AST), an FST preserves all syntax information, including comments, formatting, and whitespace. While this is powerful for refactoring, users accustomed to ASTs should be aware of this difference in tree structure and node properties when navigating and modifying the tree.
- gotcha Despite its powerful capabilities, RedBaron is officially considered in 'alpha' status and 'not battle tested yet' according to its documentation. While the public documented API is intended to be retro-compatible until version 2.0, users should be aware that the project's core might still be 'rough' and continued contributions are welcomed.
Install
-
pip install redbaron -
pip install redbaron[pygments]
Imports
- RedBaron
from redbaron import RedBaron
Quickstart
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())