Skip to content

Refactoring using the Rope API

Lie Ryan edited this page Jan 26, 2023 · 12 revisions

Audience: advanced rope user, editor plugins authors

If the IDE/editor rope integration plugin doesn't support the kind of refactoring you needed yet, but you see from the documentation that the Rope library actually already support what you wanted to do, you can try using the Rope API directly by writing a refactoring script that uses Rope as a library.

Tips: Before you actually attempt this, consider if there are other integration methods that works with your editor. For example, check if your editor supports the LSP protocol and see if pylsp-rope supports the refactoring that you wanted to do.

This is the template for what most refactoring scripts would look like:

Example for rename refactoring:

#!/usr/bin/env python
from rope.base import project
from rope.refactor import rename

proj = project.Project("/path/to/roperoot")

resource = proj.get_resource("rope/base/project.py")

offset = resource.read().index("import rope.base.fscommands") + len("import rope.base.")
# offset = --------------------------------------^

refactoring = rename.Rename(proj, resource, offset)

changes = refactoring.get_changes(
    new_name="newfscommands",
)

print(changes.get_description())
if input("Apply the changes [yn]? ").lower() == "y":
    project.do(changes)

Another example for move refactoring:

#!/usr/bin/env python
from rope.base import project
from rope.refactor import move

proj = project.Project(".")

resource = proj.get_resource("rope/base/project.py")

offset = resource.read().index('class NoProject') + len('class ')
# offset = ---------------------------^

refactoring = move.create_move(proj, resource, offset)

dest = proj.get_resource("rope/base/__init__.py")
changes = refactoring.get_changes(
    dest=dest,
)

print(changes.get_description())
if input("Apply the changes [yn]? ").lower() == "y":
    project.do(changes)

For further documentation on how to use Rope as a library, refer to Rope API documentation.

There's also some really good tour of how Rope is structured by Austin Bingham (author of Traad). The first 10 minutes of the video talked about Rope in general, the rest of the talk are more specific to Traad.