Rope#

Rope is a Python refactoring library.

Installation#

Rope can be easily installed with

$pipenv install rope

Use#

Now we first import the Project type and instantiate it with the path to the project:

[1]:
from rope.base.project import Project

proj = Project("requests")

This creates a project folder named .ropeproject in our project.

[2]:
[f.name for f in proj.get_files()]
[2]:
['hooks.py',
 'utils.py',
 '_internal_utils.py',
 'status_codes.py',
 '__version__.py',
 'sessions.py',
 'api.py',
 'cookies.py',
 'adapters.py',
 'certs.py',
 'exceptions.py',
 'api_v1.py',
 'auth.py',
 'help.py',
 'structures.py',
 'compat.py',
 'packages.py',
 '__init__.py',
 'models.py']

The proj variable can execute a number of commands such as get_files and get_file. In the following example we use this to assign the variable api to the file api.py.

[3]:
!cp requests/api.py requests/api_v1.py
[4]:
api = proj.get_file("api.py")
[5]:
from rope.refactor.rename import Rename

change = Rename(proj, api).get_changes("api.py")

proj.do(change)
[6]:
!cd requests && git status
On branch main
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:       __init__.py

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        .ropeproject/
        api_v1.py

Changes not staged for commit (use "git add" and/or "git commit -a")
[7]:
!cd requests && git diff __init__.py
diff --git a/__init__.py b/__init__.py
index f8f9429..502e33a 100644
--- a/__init__.py
+++ b/__init__.py
@@ -118,7 +118,7 @@ from .__version__ import __copyright__, __cake__
 from . import utils
 from . import packages
 from .models import Request, Response, PreparedRequest
-from .api import request, get, head, post, patch, put, delete, options
+from .api_v1 import request, get, head, post, patch, put, delete, options
 from .sessions import session, Session
 from .status_codes import codes
 from .exceptions import (

With proj.do(change), the file requests/__init__.py has been changed to import from new_api instead of api.

Rope can be used not only for renaming files, but also in various other cases; see also Rope Refactorings.