A comprehensive Python refactoring library providing powerful and safe code transformations, analysis, and IDE integration capabilities.
—
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.
All rope refactorings follow this consistent pattern:
get_changes() with parametersproject.do(changes)Rename variables, functions, classes, modules, and packages with full scope analysis and cross-file updates.
class Rename:
"""
Rename refactoring for identifiers at any scope.
Parameters:
- project (Project): Project instance
- resource (Resource): File containing the identifier
- offset (int): Character offset of identifier to rename
"""
def __init__(self, project, resource, offset): ...
def get_old_name(self):
"""
Get the current name of the identifier.
Returns:
str: Current identifier name
"""
def get_changes(self, new_name, in_file=None, in_hierarchy=False, unsure=None, docs=False, resources=None, task_handle=None):
"""
Generate rename changes.
Parameters:
- new_name (str): New name for the identifier
- in_file (Resource, optional): Limit changes to specific file
- in_hierarchy (bool): Rename in class hierarchy
- unsure (bool): Include uncertain occurrences
- docs (bool): Update documentation strings
- resources (list): Limit changes to specific resources
- task_handle (TaskHandle): Task handle for progress monitoring
Returns:
ChangeSet: Changes to apply the rename
Raises:
RefactoringError: If rename is not possible
BadIdentifierError: If new_name is not a valid identifier
"""Move methods, functions, variables, modules, and packages between locations.
class MoveMethod:
"""
Move method between classes.
Parameters:
- project (Project): Project instance
- resource (Resource): File containing the method
- offset (int): Character offset within the method
"""
def __init__(self, project, resource, offset): ...
def get_changes(self, destination, **kwargs):
"""
Generate move method changes.
Parameters:
- destination (str): Target class name or 'attribute'
Returns:
ChangeSet: Changes to move the method
"""
class MoveGlobal:
"""Move global functions and variables."""
def __init__(self, project, resource, offset): ...
def get_changes(self, destination, **kwargs):
"""
Move global to another module.
Parameters:
- destination (Resource): Target module resource
Returns:
ChangeSet: Changes to move the global
"""
class MoveModule:
"""Move modules and packages."""
def __init__(self, project, resource): ...
def get_changes(self, destination, **kwargs):
"""
Move module to new location.
Parameters:
- destination (Resource): Target parent folder
Returns:
ChangeSet: Changes to move the module
"""
def create_move(project, resource, offset=None):
"""
Factory function to create appropriate move refactoring.
Parameters:
- project (Project): Project instance
- resource (Resource): File containing code to move
- offset (int, optional): Character offset (None for whole module)
Returns:
Move refactoring instance (MoveMethod, MoveGlobal, or MoveModule)
"""Extract methods and variables from existing code blocks.
class ExtractMethod:
"""
Extract method from a code block.
Parameters:
- project (Project): Project instance
- resource (Resource): File containing code to extract
- start_offset (int): Start of code block to extract
- end_offset (int): End of code block to extract
"""
def __init__(self, project, resource, start_offset, end_offset): ...
def get_changes(self, extracted_name, similar=False, global_=False, kind=None):
"""
Generate extract method changes.
Parameters:
- extracted_name (str): Name for the extracted method
- similar (bool): Extract similar code blocks
- global_ (bool): Create global function instead of method
- kind (str, optional): Kind of extraction ('method', 'function')
Returns:
ChangeSet: Changes to extract the method
"""
class ExtractVariable:
"""
Extract variable from an expression.
Parameters:
- project (Project): Project instance
- resource (Resource): File containing expression
- start_offset (int): Start of expression
- end_offset (int): End of expression
"""
def __init__(self, project, resource, start_offset, end_offset): ...
def get_changes(self, variable_name, **kwargs):
"""
Generate extract variable changes.
Parameters:
- variable_name (str): Name for the extracted variable
- similar (bool): Extract similar expressions
Returns:
ChangeSet: Changes to extract the variable
"""Inline method calls, variable references, and function parameters.
class InlineMethod:
"""
Inline method calls by replacing with method body.
Parameters:
- project (Project): Project instance
- resource (Resource): File containing method definition
- offset (int): Character offset within method name
"""
def __init__(self, project, resource, offset): ...
def get_changes(self, **kwargs):
"""
Generate inline method changes.
Parameters:
- only_current (bool): Only inline current occurrence
- remove (bool): Remove method after inlining
Returns:
ChangeSet: Changes to inline the method
"""
class InlineVariable:
"""Inline variable references with their values."""
def __init__(self, project, resource, offset): ...
def get_changes(self, **kwargs):
"""
Generate inline variable changes.
Parameters:
- only_current (bool): Only inline current occurrence
- remove (bool): Remove variable after inlining
Returns:
ChangeSet: Changes to inline the variable
"""
class InlineParameter:
"""Inline function parameters with their default values."""
def __init__(self, project, resource, offset): ...
def get_changes(self, **kwargs):
"""Generate inline parameter changes."""
def create_inline(project, resource, offset):
"""
Factory function to create appropriate inline refactoring.
Parameters:
- project (Project): Project instance
- resource (Resource): File containing code to inline
- offset (int): Character offset within identifier
Returns:
Inline refactoring instance (InlineMethod, InlineVariable, or InlineParameter)
"""Modify function and method signatures including parameters, defaults, and return types.
class ChangeSignature:
"""
Change function or method signature.
Parameters:
- project (Project): Project instance
- resource (Resource): File containing function
- offset (int): Character offset within function name
"""
def __init__(self, project, resource, offset): ...
def get_changes(self, new_signature, **kwargs):
"""
Generate signature change modifications.
Parameters:
- new_signature (str): New function signature
- in_hierarchy (bool): Change in class hierarchy
Returns:
ChangeSet: Changes to update the signature
"""Advanced pattern-based restructuring for complex code transformations.
class Restructure:
"""
Advanced restructuring using search and replace patterns.
Parameters:
- project (Project): Project instance
- pattern (str): Search pattern with wildcards
- goal (str): Replacement pattern
- args (dict, optional): Pattern arguments
"""
def __init__(self, project, pattern, goal, args=None): ...
def get_changes(self, **kwargs):
"""
Generate restructuring changes.
Parameters:
- resources (list): Resources to search (None for all)
- checks (dict): Additional validation checks
Returns:
ChangeSet: Changes applying the restructuring
"""Specialized refactoring operations for object-oriented design improvements.
class EncapsulateField:
"""Create getter/setter methods for field access."""
def __init__(self, project, resource, offset): ...
def get_changes(self, **kwargs):
"""Generate field encapsulation changes."""
class IntroduceFactory:
"""Introduce factory method for object creation."""
def __init__(self, project, resource, offset): ...
def get_changes(self, factory_name, **kwargs):
"""
Generate factory method introduction changes.
Parameters:
- factory_name (str): Name for the factory method
"""
class IntroduceParameter:
"""Add new parameter to function/method."""
def __init__(self, project, resource, offset): ...
def get_changes(self, parameter, **kwargs):
"""
Generate parameter introduction changes.
Parameters:
- parameter (str): Parameter definition
"""
class LocalToField:
"""Convert local variable to instance field."""
def __init__(self, project, resource, offset): ...
def get_changes(self, **kwargs):
"""Generate local to field conversion changes."""
class MethodObject:
"""Convert method to separate class (method object pattern)."""
def __init__(self, project, resource, start_offset, end_offset): ...
def get_changes(self, class_name, **kwargs):
"""
Generate method object changes.
Parameters:
- class_name (str): Name for the method object class
"""
class UseFunction:
"""Replace inline code with function call."""
def __init__(self, project, resource, offset): ...
def get_changes(self, **kwargs):
"""Generate use function changes."""Convert between modules and packages.
class ModuleToPackage:
"""
Convert Python module to package.
Parameters:
- project (Project): Project instance
- resource (Resource): Module file to convert
"""
def __init__(self, project, resource): ...
def get_changes(self):
"""
Generate module to package conversion changes.
Returns:
ChangeSet: Changes to convert module to package
"""from rope.base.project import Project
from rope.refactor.rename import Rename
project = Project('/path/to/project')
try:
# Get file containing identifier to rename
myfile = project.get_resource('mymodule.py')
# Create rename refactoring at character offset 150
renamer = Rename(project, myfile, 150)
# Check what we're renaming
old_name = renamer.get_old_name()
print(f"Renaming '{old_name}' to 'new_name'")
# Generate changes
changes = renamer.get_changes('new_name', docs=True)
# Preview changes (optional)
print(f"Changes: {changes.get_description()}")
# Apply changes
project.do(changes)
finally:
project.close()from rope.base.project import Project
from rope.refactor.extract import ExtractMethod
project = Project('/path/to/project')
try:
# Get file with code to extract
myfile = project.get_resource('mymodule.py')
# Extract code between offsets 200-350 into a method
extractor = ExtractMethod(project, myfile, 200, 350)
# Generate changes to extract method
changes = extractor.get_changes('extracted_method', similar=True)
# Apply changes
project.do(changes)
finally:
project.close()from rope.base.project import Project
from rope.refactor.move import MoveMethod
project = Project('/path/to/project')
try:
# Get file containing method to move
myfile = project.get_resource('myclass.py')
# Create move refactoring for method at offset 300
mover = MoveMethod(project, myfile, 300)
# Move method to 'self.helper' attribute
changes = mover.get_changes('self.helper')
# Apply changes
project.do(changes)
finally:
project.close()Install with Tessl CLI
npx tessl i tessl/pypi-rope