Skip to content

Refactoring using the Rope API

Lie Ryan edited this page Dec 12, 2022 · 12 revisions

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.

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":
    changes.do()

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":
    changes.do()

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

There's also some really good tour of Rope's codebase by Austin Bingham (author of Traad).