Rope

Rope ist eine Python-Bibliothek für Refactoring.

Installation

Rope lässt sich ganz einfach mit folgendem Befehl installieren:

$ uv add rope

Verwendung

Zunächst importieren wir den Typ Project und instanziieren ihn mit dem Pfad zum Projekt:

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


proj = Project("requests")

Dadurch wird in unserem Projekt ein Projektordner mit dem Namen .ropeproject erstellt.

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

Die Variable proj kann eine Reihe von Befehlen ausführen, wie beispielsweise get_files und get_file. Im folgenden Beispiel verwenden wir dies, um der Variablen api die Datei api.py zuzuweisen.

[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 (

Mit proj.do(change) wurde die Datei requests/__init__.py so geändert, dass nun aus new_api statt aus api importiert wird.

Rope kann nicht nur zum Umbenennen von Dateien verwendet werden, sondern auch in vielen anderen Fällen; siehe auch Rope Refactorings.