AST Grep Python Bindings

0.42.1 · active · verified Sun Apr 12

ast-grep-py provides Python bindings for ast-grep, a powerful structural code search and rewrite engine. It enables developers to query and transform code using abstract syntax tree (AST) patterns, supporting multiple programming languages. The current version is 0.42.1, and the library maintains a rapid release cadence with frequent minor and patch updates, often multiple times a month.

Warnings

Install

Imports

Quickstart

Initialize an `SgRoot` with Python code, find patterns like function definitions, and replace `print()` calls with `logger.info()` using ast-grep's pattern matching syntax. Note that `replace()` returns a new `SgRoot` object.

from ast_grep_py import SgRoot

python_code = """
def my_function(a, b):
    result = a + b
    print(f"Result: {result}")
    return result
"""

# Create an SgRoot instance. Language defaults to Python.
root = SgRoot(code=python_code)

# Find all function definitions using an ast-grep pattern
# '$FUN' and '$$$' are metavariables matching identifiers and multiple statements/expressions respectively.
matches = root.find_all("def $FUN($$$):")

print("Found functions:")
for m in matches:
    print(f"- {m.text()}")

# Replace print statements with a logger.info call
# SgRoot.replace returns a new SgRoot instance with the changes.
new_code_root = root.replace(
    pattern='print($$$)',
    replacement='logger.info($$$)'
)

print("\nCode after replacement:")
print(new_code_root.text())

view raw JSON →