0
# Refactoring Operations
1
2
Comprehensive refactoring capabilities including rename, move, extract, inline, and restructure operations. All refactorings follow a standard 4-step pattern: construction, information gathering, change generation, and execution.
3
4
## Refactoring Pattern
5
6
All rope refactorings follow this consistent pattern:
7
8
1. **Construction** - Create refactoring object with project, resource, and offset
9
2. **Information** - Optionally get current state information
10
3. **Changes** - Generate changes by calling `get_changes()` with parameters
11
4. **Execution** - Apply changes using `project.do(changes)`
12
13
## Capabilities
14
15
### Rename Refactoring
16
17
Rename variables, functions, classes, modules, and packages with full scope analysis and cross-file updates.
18
19
```python { .api }
20
class Rename:
21
"""
22
Rename refactoring for identifiers at any scope.
23
24
Parameters:
25
- project (Project): Project instance
26
- resource (Resource): File containing the identifier
27
- offset (int): Character offset of identifier to rename
28
"""
29
def __init__(self, project, resource, offset): ...
30
31
def get_old_name(self):
32
"""
33
Get the current name of the identifier.
34
35
Returns:
36
str: Current identifier name
37
"""
38
39
def get_changes(self, new_name, in_file=None, in_hierarchy=False, unsure=None, docs=False, resources=None, task_handle=None):
40
"""
41
Generate rename changes.
42
43
Parameters:
44
- new_name (str): New name for the identifier
45
- in_file (Resource, optional): Limit changes to specific file
46
- in_hierarchy (bool): Rename in class hierarchy
47
- unsure (bool): Include uncertain occurrences
48
- docs (bool): Update documentation strings
49
- resources (list): Limit changes to specific resources
50
- task_handle (TaskHandle): Task handle for progress monitoring
51
52
Returns:
53
ChangeSet: Changes to apply the rename
54
55
Raises:
56
RefactoringError: If rename is not possible
57
BadIdentifierError: If new_name is not a valid identifier
58
"""
59
```
60
61
### Move Refactoring
62
63
Move methods, functions, variables, modules, and packages between locations.
64
65
```python { .api }
66
class MoveMethod:
67
"""
68
Move method between classes.
69
70
Parameters:
71
- project (Project): Project instance
72
- resource (Resource): File containing the method
73
- offset (int): Character offset within the method
74
"""
75
def __init__(self, project, resource, offset): ...
76
77
def get_changes(self, destination, **kwargs):
78
"""
79
Generate move method changes.
80
81
Parameters:
82
- destination (str): Target class name or 'attribute'
83
84
Returns:
85
ChangeSet: Changes to move the method
86
"""
87
88
class MoveGlobal:
89
"""Move global functions and variables."""
90
def __init__(self, project, resource, offset): ...
91
92
def get_changes(self, destination, **kwargs):
93
"""
94
Move global to another module.
95
96
Parameters:
97
- destination (Resource): Target module resource
98
99
Returns:
100
ChangeSet: Changes to move the global
101
"""
102
103
class MoveModule:
104
"""Move modules and packages."""
105
def __init__(self, project, resource): ...
106
107
def get_changes(self, destination, **kwargs):
108
"""
109
Move module to new location.
110
111
Parameters:
112
- destination (Resource): Target parent folder
113
114
Returns:
115
ChangeSet: Changes to move the module
116
"""
117
118
def create_move(project, resource, offset=None):
119
"""
120
Factory function to create appropriate move refactoring.
121
122
Parameters:
123
- project (Project): Project instance
124
- resource (Resource): File containing code to move
125
- offset (int, optional): Character offset (None for whole module)
126
127
Returns:
128
Move refactoring instance (MoveMethod, MoveGlobal, or MoveModule)
129
"""
130
```
131
132
### Extract Refactoring
133
134
Extract methods and variables from existing code blocks.
135
136
```python { .api }
137
class ExtractMethod:
138
"""
139
Extract method from a code block.
140
141
Parameters:
142
- project (Project): Project instance
143
- resource (Resource): File containing code to extract
144
- start_offset (int): Start of code block to extract
145
- end_offset (int): End of code block to extract
146
"""
147
def __init__(self, project, resource, start_offset, end_offset): ...
148
149
def get_changes(self, extracted_name, similar=False, global_=False, kind=None):
150
"""
151
Generate extract method changes.
152
153
Parameters:
154
- extracted_name (str): Name for the extracted method
155
- similar (bool): Extract similar code blocks
156
- global_ (bool): Create global function instead of method
157
- kind (str, optional): Kind of extraction ('method', 'function')
158
159
Returns:
160
ChangeSet: Changes to extract the method
161
"""
162
163
class ExtractVariable:
164
"""
165
Extract variable from an expression.
166
167
Parameters:
168
- project (Project): Project instance
169
- resource (Resource): File containing expression
170
- start_offset (int): Start of expression
171
- end_offset (int): End of expression
172
"""
173
def __init__(self, project, resource, start_offset, end_offset): ...
174
175
def get_changes(self, variable_name, **kwargs):
176
"""
177
Generate extract variable changes.
178
179
Parameters:
180
- variable_name (str): Name for the extracted variable
181
- similar (bool): Extract similar expressions
182
183
Returns:
184
ChangeSet: Changes to extract the variable
185
"""
186
```
187
188
### Inline Refactoring
189
190
Inline method calls, variable references, and function parameters.
191
192
```python { .api }
193
class InlineMethod:
194
"""
195
Inline method calls by replacing with method body.
196
197
Parameters:
198
- project (Project): Project instance
199
- resource (Resource): File containing method definition
200
- offset (int): Character offset within method name
201
"""
202
def __init__(self, project, resource, offset): ...
203
204
def get_changes(self, **kwargs):
205
"""
206
Generate inline method changes.
207
208
Parameters:
209
- only_current (bool): Only inline current occurrence
210
- remove (bool): Remove method after inlining
211
212
Returns:
213
ChangeSet: Changes to inline the method
214
"""
215
216
class InlineVariable:
217
"""Inline variable references with their values."""
218
def __init__(self, project, resource, offset): ...
219
220
def get_changes(self, **kwargs):
221
"""
222
Generate inline variable changes.
223
224
Parameters:
225
- only_current (bool): Only inline current occurrence
226
- remove (bool): Remove variable after inlining
227
228
Returns:
229
ChangeSet: Changes to inline the variable
230
"""
231
232
class InlineParameter:
233
"""Inline function parameters with their default values."""
234
def __init__(self, project, resource, offset): ...
235
236
def get_changes(self, **kwargs):
237
"""Generate inline parameter changes."""
238
239
def create_inline(project, resource, offset):
240
"""
241
Factory function to create appropriate inline refactoring.
242
243
Parameters:
244
- project (Project): Project instance
245
- resource (Resource): File containing code to inline
246
- offset (int): Character offset within identifier
247
248
Returns:
249
Inline refactoring instance (InlineMethod, InlineVariable, or InlineParameter)
250
"""
251
```
252
253
### Change Signature
254
255
Modify function and method signatures including parameters, defaults, and return types.
256
257
```python { .api }
258
class ChangeSignature:
259
"""
260
Change function or method signature.
261
262
Parameters:
263
- project (Project): Project instance
264
- resource (Resource): File containing function
265
- offset (int): Character offset within function name
266
"""
267
def __init__(self, project, resource, offset): ...
268
269
def get_changes(self, new_signature, **kwargs):
270
"""
271
Generate signature change modifications.
272
273
Parameters:
274
- new_signature (str): New function signature
275
- in_hierarchy (bool): Change in class hierarchy
276
277
Returns:
278
ChangeSet: Changes to update the signature
279
"""
280
```
281
282
### Restructure Refactoring
283
284
Advanced pattern-based restructuring for complex code transformations.
285
286
```python { .api }
287
class Restructure:
288
"""
289
Advanced restructuring using search and replace patterns.
290
291
Parameters:
292
- project (Project): Project instance
293
- pattern (str): Search pattern with wildcards
294
- goal (str): Replacement pattern
295
- args (dict, optional): Pattern arguments
296
"""
297
def __init__(self, project, pattern, goal, args=None): ...
298
299
def get_changes(self, **kwargs):
300
"""
301
Generate restructuring changes.
302
303
Parameters:
304
- resources (list): Resources to search (None for all)
305
- checks (dict): Additional validation checks
306
307
Returns:
308
ChangeSet: Changes applying the restructuring
309
"""
310
```
311
312
### Advanced Refactorings
313
314
Specialized refactoring operations for object-oriented design improvements.
315
316
```python { .api }
317
class EncapsulateField:
318
"""Create getter/setter methods for field access."""
319
def __init__(self, project, resource, offset): ...
320
321
def get_changes(self, **kwargs):
322
"""Generate field encapsulation changes."""
323
324
class IntroduceFactory:
325
"""Introduce factory method for object creation."""
326
def __init__(self, project, resource, offset): ...
327
328
def get_changes(self, factory_name, **kwargs):
329
"""
330
Generate factory method introduction changes.
331
332
Parameters:
333
- factory_name (str): Name for the factory method
334
"""
335
336
class IntroduceParameter:
337
"""Add new parameter to function/method."""
338
def __init__(self, project, resource, offset): ...
339
340
def get_changes(self, parameter, **kwargs):
341
"""
342
Generate parameter introduction changes.
343
344
Parameters:
345
- parameter (str): Parameter definition
346
"""
347
348
class LocalToField:
349
"""Convert local variable to instance field."""
350
def __init__(self, project, resource, offset): ...
351
352
def get_changes(self, **kwargs):
353
"""Generate local to field conversion changes."""
354
355
class MethodObject:
356
"""Convert method to separate class (method object pattern)."""
357
def __init__(self, project, resource, start_offset, end_offset): ...
358
359
def get_changes(self, class_name, **kwargs):
360
"""
361
Generate method object changes.
362
363
Parameters:
364
- class_name (str): Name for the method object class
365
"""
366
367
class UseFunction:
368
"""Replace inline code with function call."""
369
def __init__(self, project, resource, offset): ...
370
371
def get_changes(self, **kwargs):
372
"""Generate use function changes."""
373
```
374
375
### Module Conversion
376
377
Convert between modules and packages.
378
379
```python { .api }
380
class ModuleToPackage:
381
"""
382
Convert Python module to package.
383
384
Parameters:
385
- project (Project): Project instance
386
- resource (Resource): Module file to convert
387
"""
388
def __init__(self, project, resource): ...
389
390
def get_changes(self):
391
"""
392
Generate module to package conversion changes.
393
394
Returns:
395
ChangeSet: Changes to convert module to package
396
"""
397
```
398
399
## Usage Examples
400
401
### Basic Rename Refactoring
402
403
```python
404
from rope.base.project import Project
405
from rope.refactor.rename import Rename
406
407
project = Project('/path/to/project')
408
409
try:
410
# Get file containing identifier to rename
411
myfile = project.get_resource('mymodule.py')
412
413
# Create rename refactoring at character offset 150
414
renamer = Rename(project, myfile, 150)
415
416
# Check what we're renaming
417
old_name = renamer.get_old_name()
418
print(f"Renaming '{old_name}' to 'new_name'")
419
420
# Generate changes
421
changes = renamer.get_changes('new_name', docs=True)
422
423
# Preview changes (optional)
424
print(f"Changes: {changes.get_description()}")
425
426
# Apply changes
427
project.do(changes)
428
429
finally:
430
project.close()
431
```
432
433
### Extract Method Refactoring
434
435
```python
436
from rope.base.project import Project
437
from rope.refactor.extract import ExtractMethod
438
439
project = Project('/path/to/project')
440
441
try:
442
# Get file with code to extract
443
myfile = project.get_resource('mymodule.py')
444
445
# Extract code between offsets 200-350 into a method
446
extractor = ExtractMethod(project, myfile, 200, 350)
447
448
# Generate changes to extract method
449
changes = extractor.get_changes('extracted_method', similar=True)
450
451
# Apply changes
452
project.do(changes)
453
454
finally:
455
project.close()
456
```
457
458
### Move Method Refactoring
459
460
```python
461
from rope.base.project import Project
462
from rope.refactor.move import MoveMethod
463
464
project = Project('/path/to/project')
465
466
try:
467
# Get file containing method to move
468
myfile = project.get_resource('myclass.py')
469
470
# Create move refactoring for method at offset 300
471
mover = MoveMethod(project, myfile, 300)
472
473
# Move method to 'self.helper' attribute
474
changes = mover.get_changes('self.helper')
475
476
# Apply changes
477
project.do(changes)
478
479
finally:
480
project.close()
481
```