Rope

1.14.0 · active · verified Sat Apr 11

Rope is an advanced, open-source Python refactoring library. It provides extensive APIs for performing various code transformations like renaming, extracting methods, and moving elements. Actively maintained, it sees regular updates with recent releases like 1.14.0, and supports modern Python versions.

Warnings

Install

Imports

Quickstart

This example demonstrates how to initialize a Rope project, load a Python file, and perform a simple variable renaming refactoring. It creates a temporary file and directory, renames a variable 'old_name' to 'new_name', applies the changes, and then cleans up. The `Project` object manages the codebase, `Resource` objects represent files, and specific refactoring classes (like `Rename`) perform transformations.

import os
import tempfile
import shutil
from pathlib import Path
from rope.base.project import Project
from rope.base.resources import File
from rope.refactor.rename import Rename

# Create a temporary directory and a dummy Python file
temp_dir = Path(tempfile.mkdtemp())
file_path = temp_dir / "my_module.py"
file_path.write_text("""
def greet():
    old_name = "World"
    print(f"Hello, {old_name}!")
""")

project = Project(temp_dir)
resource = project.get_resource(file_path.name)

# Find the start offset of 'old_name'
# In '    old_name = "World"', 'old_name' starts at index 5
offset = file_path.read_text().find('old_name = "World"') + 4

# Perform rename refactoring
changes = Rename(project, resource, offset).get_changes('new_name')

# Apply the changes to the project files
project.do(changes)

# Verify the change
print(file_path.read_text())

# Clean up
project.close()
shutil.rmtree(temp_dir)

view raw JSON →