Baron: Full Syntax Tree for Python
Baron is a Full Syntax Tree (FST) library for Python, designed for refactoring and detailed code analysis. Unlike an Abstract Syntax Tree (AST) which discards some syntax information, Baron's FST preserves all original formatting, including comments, empty lines, and spacing, ensuring that converting code to an FST and back exactly reproduces the original source code. The current version is 0.10.1, released in December 2021. Development is active with a focus on bug fixes, minor feature additions, and performance improvements, indicating a measured release cadence.
Warnings
- gotcha Baron provides a low-level Full Syntax Tree (FST). For most high-level refactoring and code manipulation tasks, it is strongly recommended to use `RedBaron` instead, which offers a more user-friendly and object-oriented API built on top of Baron.
- breaking In version 0.9, the structure for annotations changed. Annotations are now members of `{def,list,dict}_argument` nodes to flatten the data structure, which may break code relying on the previous FST structure for annotated elements.
- breaking Version 0.6 introduced significant FST structure modifications. Specifically, `def_argument_tuple` nodes were removed, and argument structures became more coherent; the `name` attribute of a `def_argument` node was renamed to `target`, which now points to a dictionary instead of a string.
- gotcha Baron officially supports Python 2 grammar and up to Python 3.7 grammar. Newer Python versions (3.8+) and their syntax features might not be fully supported, potentially leading to parsing errors or an incomplete FST.
Install
-
pip install baron
Imports
- parse
from baron import parse
- dumps
from baron import dumps
Quickstart
from baron import parse, dumps
source_code = "def example_func(x):\n return x + 1 # A simple function"
fst = parse(source_code)
# You would typically manipulate the `fst` object here.
# For most refactoring tasks, it's recommended to use RedBaron,
# which provides a higher-level API built on top of Baron.
# For example:
# from redbaron import RedBaron
# red = RedBaron(source_code)
# red.find_node('name', value='example_func').value = 'new_name'
# modified_code = red.dumps()
regenerated_code = dumps(fst)
print("Original code:\n" + source_code)
print("\nRegenerated code from FST:\n" + regenerated_code)
assert source_code == regenerated_code