Skip to content

Refactoring using the Rope API

Lie Ryan edited this page Nov 28, 2022 · 12 revisions

If your IDE/editor doesn't support the kind of refactoring you needed yet, you can try using the Rope API directly.

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.

Clone this wiki locally