OpenRewrite Python

8.79.5 · active · verified Thu Apr 16

OpenRewrite provides a powerful framework for automated code refactoring and static analysis. The `openrewrite` Python library offers Python bindings and a Command Line Interface (CLI) to leverage the core OpenRewrite engine, enabling programmatic application of recipes for code transformation in Python projects. It is currently at version 8.79.5 and follows the core OpenRewrite project's release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a basic OpenRewrite Python recipe and execute it using `rewrite_run`. It creates a temporary Python file, applies a no-op recipe in dry-run mode, and then cleans up. Critical prerequisites are a Java 11+ Runtime Environment and the OpenRewrite CLI, which the Python library orchestrates.

import os
import pathlib
from openrewrite.recipe import Recipe
from openrewrite.run import rewrite_run
from openrewrite.tree import SourceFile

# Create a dummy Python file for the recipe to process
dummy_file_path = pathlib.Path("example_for_rewrite.py")
with open(dummy_file_path, "w") as f:
    f.write("print('Hello, OpenRewrite!')\n")
    f.write("import os # This import will be processed by a real recipe\n")

class MyPythonRecipe(Recipe):
    def get_display_name(self) -> str:
        return "My First Python Recipe"

    def get_description(self) -> str:
        return "A simple recipe that does nothing, demonstrating the API."

    def visit_source_file(self, source_file: SourceFile, execution_context) -> SourceFile:
        # In a real recipe, you would inspect and modify the source_file here.
        # For this example, we just print the path and return it unchanged.
        print(f"[Recipe] Visiting file: {source_file.get_source_path()}")
        return source_file

# --- IMPORTANT: Ensure OpenRewrite CLI and Java 11+ are installed and in PATH ---
# The `rewrite_run` function calls the `rewrite` CLI tool internally.
# If you encounter FileNotFoundError or Java-related errors, check your setup.

try:
    print(f"Running recipe on {dummy_file_path} (dry_run=True)...")
    results = rewrite_run(
        [MyPythonRecipe()],
        [str(dummy_file_path)], # List of file paths to process
        dry_run=True, # Set to False to apply changes directly to files
        # For more complex scenarios, you might use an InMemoryExecutionContext:
        # execution_context=InMemoryExecutionContext()
    )
    print("Recipe run complete.")
    if not results:
        print("No changes detected (as expected for this basic recipe in dry_run mode).")
    else:
        print("Changes detected (this might indicate an issue with the dummy recipe or environment setup if unexpected).")

except Exception as e:
    print(f"An error occurred during rewrite_run. Please ensure OpenRewrite CLI and Java 11+ are installed and in PATH.\nError: {e}")

finally:
    # Clean up the dummy file
    if dummy_file_path.exists():
        os.remove(dummy_file_path)
        print(f"Cleaned up {dummy_file_path}.")

view raw JSON →