### Setup Local Development Environment for Rope Source: https://github.com/python-rope/rope/blob/master/docs/contributing.md Commands to clone the repository, create a virtual environment, and install the project dependencies for development. ```bash git clone https://github.com/python-rope/rope.git python -m venv rope-venv # Activate the virtualenv pip install -e '.[doc,dev]' ``` -------------------------------- ### Restructuring Pattern Example Source: https://github.com/python-rope/rope/blob/master/docs/dev/issues.md Demonstrates the syntax for defining a pattern, goal, and before-replacement logic for code restructuring within the Rope framework. ```default pattern: ${a} if ${b} else ${c} goal: replacement before: if ${b}: replacement = ${a} else: replacement = ${c} ``` -------------------------------- ### Work with Project Resources Source: https://context7.com/python-rope/rope/llms.txt Explains how to work with resources (files and folders) within a Rope project using the libutils module. It covers getting existing resources, creating new file/folder resources, accessing resource properties like path and type, reading/writing file content, getting the module name, and checking if a resource is a Python file. ```python from rope.base.project import Project from rope.base import libutils project = Project('/path/to/myproject') # Get a resource for an existing file resource = libutils.path_to_resource(project, '/path/to/myproject/module.py') # Create resource for a file that doesn't exist yet new_file = libutils.path_to_resource(project, '/path/to/myproject/new_module.py', type='file') new_folder = libutils.path_to_resource(project, '/path/to/myproject/new_package', type='folder') # Resource properties print(f"Path: {resource.path}") # Relative to project root print(f"Real path: {resource.real_path}") # Absolute path on filesystem print(f"Is folder: {resource.is_folder()}") # Read and write file contents content = resource.read() resource.write("# New content\nprint('Hello')\n") # Get module name from resource module_name = libutils.modname(resource) # Returns 'package.module' # Check if resource is a Python file is_python = libutils.is_python_file(project, resource) project.close() ``` -------------------------------- ### Perform Rename Refactoring in Python Source: https://github.com/python-rope/rope/blob/master/docs/library.md Shows how to use the `Rename` class from `rope.refactor.rename` to rename an element in the project. It involves creating a `Rename` object with the project, resource, and offset, then getting and applying changes. The example also demonstrates undoing the refactoring. ```python from rope.base.project import Project from rope.refactor.rename import Rename project = Project('.') mod1 = project.root.create_file('mod1.py') mod1.write('a_var = 10\n') changes = Rename(project, mod1, 1).get_changes('new_var') project.do(changes) project.history.undo() project.close() ``` -------------------------------- ### Build Python Package with build Source: https://github.com/python-rope/rope/blob/master/ropetest-package-fixtures/external_fixturepkg/README.md This command builds the Python package for distribution. It utilizes the 'build' module to create distributable archives (like wheels and sdists) typically found in the 'dist' folder. Ensure you have the 'build' package installed (`pip install build`). ```bash python -m build ``` -------------------------------- ### Get Resource at a Specific Path in Python Source: https://github.com/python-rope/rope/blob/master/docs/library.md This function retrieves a resource (file or folder) located at a specified path within the project. It can also be used to represent non-existent resources by specifying their type. ```python myfile = libutils.path_to_resource(myproject, '/path/to/file.py') # Resource for a non-existing folder. new_folder = libutils.path_to_resource(myproject, '/path/to/folder', type='folder') ``` -------------------------------- ### POST /rope/project Source: https://github.com/python-rope/rope/blob/master/docs/library.md Initializes a new Rope project instance at a specified file system path. ```APIDOC ## POST /rope/project ### Description Creates a new project instance to manage refactoring operations. A project is a folder in the file system that Rope uses to index and analyze Python modules. ### Method POST ### Endpoint rope.base.project.Project(path, ropefolder='.ropeproject', **kwargs) ### Parameters #### Path Parameters - **path** (string) - Required - The absolute or relative file system path to the project directory. #### Request Body - **ropefolder** (string) - Optional - The name of the folder used for storing project metadata (default: '.ropeproject'). Set to None to disable. - **kwargs** (dict) - Optional - Configuration parameters that override settings in .ropeproject/config.py. ### Request Example { "path": "/path/to/myproject", "ropefolder": ".ropeproject" } ### Response #### Success Response (200) - **project** (object) - A configured Project instance. #### Response Example { "status": "success", "project_path": "/path/to/myproject" } ``` -------------------------------- ### Initialize Rope Project Source: https://context7.com/python-rope/rope/llms.txt Demonstrates how to initialize a Rope project, which represents a folder containing Python modules and packages. It covers creating a project with default settings, custom settings like rope folder and ignored resources, accessing project properties, and retrieving Python files. Remember to close the project when done. ```python from rope.base.project import Project # Create a project pointing to your Python project root project = Project('/path/to/myproject') # Project with custom settings project = Project( '/path/to/myproject', ropefolder='.ropeproject', # Folder for rope's data (None to disable) ignored_resources=['*.pyc', '__pycache__', '.git'], python_path=['/path/to/extra/libs'] ) # Access project properties print(f"Project root: {project.address}") print(f"Root folder: {project.root}") # Get all Python files in the project python_files = project.get_python_files() for f in python_files: print(f"Python file: {f.path}") # Always close the project when done project.close() ``` -------------------------------- ### Create a Rope Project Instance Source: https://github.com/python-rope/rope/blob/master/docs/library.md This code demonstrates how to instantiate a Rope project object, which requires the root address of the project directory. ```python project = Project(root_address) ``` -------------------------------- ### Get Path Relative to Project Root in Python Source: https://github.com/python-rope/rope/blob/master/docs/library.md This function calculates and returns the path of a file or folder relative to the project's root directory. ```python relpath = libutils.relative(myproject.address, path) ``` -------------------------------- ### Implement IDE Code Assistance Source: https://context7.com/python-rope/rope/llms.txt Shows how to retrieve code completion proposals, documentation, definition locations, and calltips for a given source code snippet within a project context. ```python from rope.base.project import Project from rope.base import libutils from rope.contrib import codeassist project = Project('/path/to/myproject') resource = libutils.path_to_resource(project, '/path/to/myproject/module.py') source_code = 'import os\n\nclass MyClass:\n def my_method(self):\n self.value = 42\n\nobj = MyClass()\nobj.my_' offset = len(source_code) - 1 # Get completions proposals = codeassist.code_assist(project, source_code, offset, resource=resource) sorted_proposals = codeassist.sorted_proposals(proposals) # Get documentation and definition doc = codeassist.get_doc(project, source_code, source_code.index('MyClass') + 1) location = codeassist.get_definition_location(project, source_code, source_code.index('my_method') + 1) project.close() ``` -------------------------------- ### Get Dotted Module Path from Resource in Python Source: https://github.com/python-rope/rope/blob/master/docs/library.md This utility retrieves the fully qualified dotted path string for the module associated with a given resource. ```python module_name = libutils.modname(resource) ``` -------------------------------- ### Configure pylsp-rope with Neovim Native LSP Source: https://github.com/python-rope/rope/wiki/Rope-in-Vim-or-Neovim Sets up the native Neovim LSP client to use pylsp and defines a buffer-local keymap for triggering code actions. ```lua local nvim_lsp = require('lspconfig') local on_attach = function(client, bufnr) local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end local opts = { noremap=true, silent=true } buf_set_keymap('n', 'ca', 'lua vim.lsp.buf.code_action()', opts) end require'lspconfig'.pylsp.setup{ cmd = { "pylsp" }, on_attach = on_attach, } ``` -------------------------------- ### Get Global Scope from Code String in Python Source: https://github.com/python-rope/rope/blob/master/docs/library.md This function retrieves the outermost scope (GlobalScope) for a given code string, representing the entire module's scope. ```python scope = libutils.get_string_scope(myproject, source) ``` -------------------------------- ### Create Resource Objects in Rope Source: https://github.com/python-rope/rope/blob/master/docs/library.md Demonstrates two methods to create a Resource object for a project path. Using libutils.path_to_resource is recommended for its flexibility and ability to handle non-existent paths. ```python from rope.base import project myresource = myproject.get_resource('/path/to/resource') ``` ```python from rope.base import libutils myresource = libutils.path_to_resource(myproject, '/path/to/resource') ``` -------------------------------- ### Define Type Hints using Sphinx Style Source: https://github.com/python-rope/rope/blob/master/docs/overview.md Demonstrates how to use Sphinx-style docstrings to define parameter and return types for code completion in Rope. ```python def myfunction(node, foo): """Do something with a ``node``. :type node: ProgramNode :param str foo: foo parameter description """ node. ``` -------------------------------- ### Get PyModule Object from Code String in Python Source: https://github.com/python-rope/rope/blob/master/docs/library.md This utility function generates a rope.base.pyobjects.PyModule object from a given source code string. It can optionally associate the code with a resource and control how syntax errors are handled. ```python pymodule = libutils.get_string_module(myproject, source) ``` -------------------------------- ### Initialize a Rope Project Source: https://github.com/python-rope/rope/blob/master/docs/library.md Creates a new Rope project instance pointing to a specific directory. This project object serves as the base for all subsequent refactoring and analysis tasks. ```python import rope.base.project myproject = rope.base.project.Project('/path/to/myproject') ``` -------------------------------- ### Apply Restructure Refactoring in Python Source: https://github.com/python-rope/rope/blob/master/docs/library.md Illustrates how to use the `Restructure` class from `rope.refactor.restructure` to transform code patterns. It involves defining a pattern, a goal, and arguments, then creating a `Restructure` object and applying the changes. This example specifically shows replacing a `pow` function call with the `**` operator. ```python from rope.base.project import Project from rope.refactor import restructure project = Project('.') mod1 = project.root.create_file('mod1.py') mod1.write('def pow(x, y):\n result = 1\n' \ ' for i in range(y):\n result *= x\n' \ ' return result\n') mod2 = project.root.create_file('mod2.py') mod2.write('import mod1\nprint(mod1.pow(2, 3))\n') pattern = '${pow_func}(${param1}, ${param2})' goal = '${param1} ** ${param2}' args = {'pow_func': 'name=mod1.pow'} restructuring = restructure.Restructure(project, pattern, goal, args) project.do(restructuring.get_changes()) mod1.remove() mod2.remove() project.close() ``` -------------------------------- ### Configure AutoImport with SQLite Source: https://github.com/python-rope/rope/blob/master/docs/library.md Shows how to initialize the sqlite3-based AutoImport module, generate caches for local and external modules, and search for importable names. ```python from rope.base.project import Project from rope.contrib.autoimport import AutoImport project = Project("/path/to/project") autoimport = AutoImport(project, memory=False) autoimport.generate_resource_cache() autoimport.generate_modules_cache() print(autoimport.search("Dict")) autoimport.close() project.close() ``` -------------------------------- ### Legacy Rope Configuration File Source: https://github.com/python-rope/rope/blob/master/docs/configuration.md A sample configuration file structure for older versions of Rope. While functional, it is recommended to use the latest configuration patterns provided in the documentation. ```python # The default ``config.py`` # Add your configuration settings here ``` -------------------------------- ### Define Type Hints using Numpydoc Style Source: https://github.com/python-rope/rope/blob/master/docs/overview.md Illustrates the Numpydoc format for documenting parameters and types, requiring the numpydoc package. ```python def foo(var1, var2, long_var_name='hi'): r"""A one-line summary. Parameters ---------- var1 : array_like var2 : int long_variable_name : {'hi', 'ho'}, optional """ var2. ``` -------------------------------- ### Create and Apply Move Refactoring in Python Source: https://github.com/python-rope/rope/blob/master/docs/library.md Demonstrates how to create a move refactoring object using `create_move` and apply the changes to the project. It requires a project, resource, and offset for the source location, and a destination resource for the move. ```python from rope.refactor.move import create_move mover = create_move(project, resource, offset) project.do(mover.get_changes(destination)) ``` -------------------------------- ### Project-wide Code Restructuring Source: https://context7.com/python-rope/rope/llms.txt Demonstrates how to perform global code transformations using pattern matching and wildcards. This is useful for replacing specific function calls or syntax patterns across the entire project. ```python from rope.refactor.restructure import Restructure pattern = '${pow_func}(${base}, ${exp})' goal = '${base} ** ${exp}' args = {'pow_func': 'name=math.pow'} restructuring = Restructure(project, pattern, goal, args) changes = restructuring.get_changes() project.do(changes) ``` -------------------------------- ### Utilize Code Assistance with rope.contrib.codeassist Source: https://github.com/python-rope/rope/blob/master/docs/library.md Demonstrates how to retrieve code completion proposals, sort them, and apply them to source code using the rope.contrib.codeassist module. ```python from rope.ide import codeassist proposals = codeassist.code_assist(project, source_code, offset) proposals = codeassist.sorted_proposals(proposals) starting_offset = codeassist.starting_offset(source_code, offset) proposal = proposals[x] replacement = proposal.name new_source_code = (source_code[:starting_offset] + replacement + source_code[offset:]) ``` -------------------------------- ### Apply Refactoring Changes Source: https://github.com/python-rope/rope/blob/master/docs/library.md Demonstrates how to apply calculated refactoring changes to a project using the project.do method. ```python myproject.do(changes) ``` -------------------------------- ### Monitor and Control Tasks with TaskHandle Source: https://github.com/python-rope/rope/blob/master/docs/library.md Demonstrates how to use TaskHandle to observe progress of refactoring tasks and how to programmatically stop a running task. Observers can be added to track job set status and completion percentages. ```python import rope.base.taskhandle handle = rope.base.taskhandle.TaskHandle("Test Task") def update_progress(): jobset = handle.current_jobsets() if jobset: text = '' if jobset.get_name() is not None: text += jobset.get_name() if jobset.get_active_job_name() is not None: text += ' : ' + jobset.get_active_job_name() percent = jobset.get_percent_done() if percent is not None: text += ' ... %s percent done' % percent print(text) handle.add_observer(update_progress) changes = renamer.get_changes('new_name', task_handle=handle) def stop(): handle.stop() ``` -------------------------------- ### Extract Method as Class or Static Method Source: https://github.com/python-rope/rope/blob/master/docs/overview.md Shows how to create classmethods or staticmethods by prefixing the method name with @ or $ during extraction. ```python class A(object): @staticmethod def f(a): b = A.twice(a) @staticmethod def twice(a): return a * 2 ``` -------------------------------- ### Configure Rope with pytool.toml Source: https://github.com/python-rope/rope/blob/master/docs/configuration.md This snippet illustrates the configuration using `pytool.toml`, which is used when neither `pyproject.toml` nor `config.py` are present. It follows the same syntax as `pyproject.toml` for setting Rope preferences. ```toml # pytool.toml configuration follows the same syntax as pyproject.toml # Example: # [tool.rope] # split_imports = true ``` -------------------------------- ### Use Function Refactoring Source: https://github.com/python-rope/rope/blob/master/docs/overview.md Demonstrates how to identify code patterns that match an existing function and replace them with calls to that function. ```python def square(p): return p ** 2 my_var = square(3) ``` -------------------------------- ### Initialize and Perform Cross-Project Refactoring Source: https://github.com/python-rope/rope/blob/master/docs/library.md This snippet shows the initialization of a refactoring instance for a specific project and resource, followed by obtaining and performing changes across all dependent projects. It highlights the use of `get_all_changes()` and `multiproject.perform()` for multi-project operations. ```python renamer = CrossRename(project, resource, offset) project_and_changes = renamer.get_all_changes('newname') multiproject.perform(project_and_changes) ``` -------------------------------- ### Configure Rope with config.py - Project Opened Hook Source: https://github.com/python-rope/rope/blob/master/docs/configuration.md This Python snippet shows how to define a `project_opened` function in `config.py`. This function is executed after a project is opened, allowing for custom startup actions. ```python def project_opened(project): """This function is called after opening the project""" # Do whatever you like here! ``` -------------------------------- ### Configure pylsp-rope with vim-lsp Source: https://github.com/python-rope/rope/wiki/Rope-in-Vim-or-Neovim Registers the pylsp server with vim-lsp and defines key mappings for code actions like refactoring, inlining, and organizing imports. ```vim autocmd User lsp_setup call lsp#register_server({ \ 'name': 'pylsp', \ 'cmd': {server_info->['pylsp']}, \ 'whitelist': ['python'], \ }) function! s:on_lsp_buffer_enabled() abort nmap (lsp-code-action) vmap :LspCodeAction nmap ri :LspCodeAction refactor.inline nmap ro :LspCodeAction source.organizeImports vmap rm :LspCodeAction refactor.extract nmap rm :LspCodeAction refactor.extract endfunction augroup lsp_install autocmd! autocmd User lsp_buffer_enabled call s:on_lsp_buffer_enabled() augroup END ``` -------------------------------- ### Dynamic Object Analysis (DOA) Implementation Source: https://github.com/python-rope/rope/blob/master/docs/overview.md Illustrates how running modules via PyCore.run_module() allows Rope to collect runtime type information that static analysis cannot detect. ```python # mod1.py def f1(param): pass # mod2.py import mod1 class A(object): def a_method(self): pass a_var = A() mod1.f1(a_var) ``` -------------------------------- ### Custom Restructuring Wildcard Pattern Source: https://github.com/python-rope/rope/blob/master/docs/dev/issues.md Illustrates the proposed syntax for using type-constrained wildcards within restructuring patterns to improve matching precision. ```default pattern: ${project:type=rope.base.project.Project}.pycore ``` -------------------------------- ### Configure pylsp-rope with coc.nvim Source: https://github.com/python-rope/rope/wiki/Rope-in-Vim-or-Neovim Configures the coc.nvim language server settings to include pylsp and maps the code action trigger. ```json { "languageserver": { "python": { "command": "python3", "args": ["-mpylsp"], "filetypes": ["python"], "settings": { "pylsp": { "plugins": { "pylsp_rope": { "enabled": true } } } } } } } ``` ```vim map ca (coc-codeaction-selected) ``` -------------------------------- ### Implement Custom FileSystemCommands Source: https://github.com/python-rope/rope/blob/master/docs/library.md Defines a custom class to handle file system operations within a Rope project. This is useful for IDEs that need to manage file changes independently. ```python class MyFileSystemCommands(object): def create_file(self, path): pass def create_folder(self, path): pass def move(self, path, new_location): pass def remove(self, path): pass def write(self, path, data): pass def read(self, path): pass my_fscommands = MyFileSystemCommands() project = rope.base.project.Project('~/myproject', fscommands=my_fscommands) ``` -------------------------------- ### Configure Rope with pyproject.toml Source: https://github.com/python-rope/rope/blob/master/docs/configuration.md This snippet shows how to configure Rope using the `pyproject.toml` file. It enables split imports and defines aliases for modules like `datetime` and `multiprocessing`. ```toml [tool.rope] split_imports = true autoimport.aliases = [ ['dt', 'datetime'], ['mp', 'multiprocessing'], ] ``` -------------------------------- ### Python: Move Refactoring with Rope API Source: https://github.com/python-rope/rope/wiki/Refactoring-using-the-Rope-API This script shows how to execute a move refactoring using the Rope library. It sets up a Rope project, locates the resource and offset to be moved, specifies the destination, and applies the move operation after user confirmation. ```python #!/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": project.do(changes) ``` -------------------------------- ### Create Cross-Project Rename Refactoring Constructor Source: https://github.com/python-rope/rope/blob/master/docs/library.md This code demonstrates how to create a constructor for a cross-project rename refactoring. It utilizes `multiproject.MultiProjectRefactoring` by passing the specific refactoring class (e.g., `rename.Rename`) and a list of dependent projects. ```python from rope.refactor import multiproject, rename CrossRename = multiproject.MultiProjectRefactoring(rename.Rename, projects) ``` -------------------------------- ### Project Configuration Options Source: https://github.com/python-rope/rope/blob/master/docs/configuration.md This section describes the configuration options for a Rope project, which control how Rope analyzes and interacts with your Python codebase. ```APIDOC ## Project Configuration Options ### Description This section describes the configuration options for a Rope project, which control how Rope analyzes and interacts with your Python codebase. ### Options #### ignored_resources - **Type**: List[str] - **Description**: Specify which files and folders to ignore in the project. Changes to ignored resources are not added to the history and VCSs. Also they are not returned in `Project.get_files()`. Note that `?` and `*` match all characters but slashes. `*.pyc`: matches `test.pyc` and `pkg/test.pyc` `mod*.pyc`: matches `test/mod1.pyc` but not `mod/1.pyc` `.svn`: matches `pkg/.svn` and all of its children `build/*.o`: matches `build/lib.o` but not `build/sub/lib.o` `build//*.o`: matches `build/lib.o` and `build/sub/lib.o` - **Default**: [’

```
*
```

.pyc’, ‘

```
*
```

~’, ‘.ropeproject’, ‘.hg’, ‘.svn’, ‘_svn’, ‘.git’, ‘.tox’, ‘.venv’, ‘venv’, ‘.mypy_cache’, ‘.pytest_cache’] #### python_files - **Type**: List[str] - **Description**: Specifies which files should be considered python files. It is useful when you have scripts inside your project. Only files ending with `.py` are considered to be python files by default. - **Default**: [’

```
*
```

.py’] #### source_folders - **Type**: List[str] - **Description**: Custom source folders: By default rope searches the project for finding source folders (folders that should be searched for finding modules). You can add paths to that list. Note that rope guesses project source folders correctly most of the time; use this if you have any problems. The folders should be relative to project root and use `/` for separating folders regardless of the platform rope is running on. `src/my_source_folder` for instance. - **Default**: [] #### python_path - **Type**: List[str] - **Description**: You can extend python path for looking up modules. - **Default**: [] ``` -------------------------------- ### Perform Code Restructuring with Rope Source: https://context7.com/python-rope/rope/llms.txt Demonstrates how to use the Restructure class to perform pattern-based code transformations, including method replacement, adding imports, and multi-line statement refactoring. ```python from rope.base.project import Project from rope.refactor.restructure import Restructure project = Project('.') # Replace deprecated method calls restructuring = Restructure(project, '${obj}.old_method(${args})', '${obj}.new_method(${args})', {'obj': 'type=mymodule.MyClass'}) project.do(restructuring.get_changes()) # Add imports with restructuring restructuring = Restructure(project, '${dict_obj}.iteritems()', '${dict_obj}.items()', imports=['from __future__ import print_function']) project.do(restructuring.get_changes()) # Multiple statement replacement pattern = '${logger}.debug(${msg})\n${logger}.debug(${msg2})' goal = '${logger}.debug(${msg} + " | " + ${msg2})' project.do(Restructure(project, pattern, goal).get_changes()) project.close() ``` -------------------------------- ### Configure pylsp-rope with ALE Source: https://github.com/python-rope/rope/wiki/Rope-in-Vim-or-Neovim Configures the ALE plugin to use pylsp as a linter for Python files. ```vim let g:ale_linters = { \ 'python': ['pylsp'], \} ``` -------------------------------- ### Move Refactoring for Modules and Classes Source: https://context7.com/python-rope/rope/llms.txt Shows how to move classes, functions, or entire modules to different locations using create_move and MoveModule. This automatically updates imports and references across the project. ```python from rope.refactor.move import create_move, MoveModule # Move class or function offset = source.read().index('MyClass') mover = create_move(project, source, offset) changes = mover.get_changes(dest) project.do(changes) # Move module module_mover = MoveModule(project, module) changes = module_mover.get_changes(pkg) project.do(changes) ``` -------------------------------- ### Configure Rope with config.py - Ignored Resources Source: https://github.com/python-rope/rope/blob/master/docs/configuration.md This Python snippet demonstrates how to configure ignored resources in Rope using a `config.py` file. It lists file patterns and directories that Rope should not process. ```python def set_prefs(prefs): prefs["ignored_resources"] = [ "*.pyc", "*~", ".ropeproject", ".hg", ".svn", "_svn", ".git", ".tox", ".venv", "venv", ] ``` -------------------------------- ### Monitor and Cancel Refactoring Tasks Source: https://context7.com/python-rope/rope/llms.txt Demonstrates how to use TaskHandle to track the progress of refactoring operations. It includes an observer callback for status updates and shows how to trigger cancellation from a separate thread. ```python handle = taskhandle.TaskHandle("Rename Refactoring") def progress_callback(): jobset = handle.current_jobset() if jobset: print(f"{jobset.get_name()} - {jobset.get_active_job_name()} ({jobset.get_percent_done()}% done)") handle.add_observer(progress_callback) renamer = Rename(project, resource, 10) changes = renamer.get_changes('new_name', task_handle=handle) project.do(changes, task_handle=handle) ``` -------------------------------- ### Python: Rename Refactoring with Rope API Source: https://github.com/python-rope/rope/wiki/Refactoring-using-the-Rope-API This script demonstrates how to perform a rename refactoring using the Rope library's API. It initializes a Rope project, identifies the resource and offset for the refactoring, applies the rename operation, and prompts the user to confirm the changes. ```python #!/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": project.do(changes) ``` -------------------------------- ### Core Project Management and Refactoring Source: https://context7.com/python-rope/rope/llms.txt This section details the fundamental usage of the Project class for managing files, performing refactorings, and handling changes. ```APIDOC ## Project Class and Refactoring Workflow ### Description Demonstrates how to initialize a Project, perform a refactoring (e.g., Rename), compute changes, and apply them. ### Method Illustrative Python code ### Endpoint N/A (Library usage) ### Parameters N/A ### Request Example ```python from rope.base import project from rope.refactor import rename # Initialize a project proj = project.Project('path/to/your/project') # Get a resource (e.g., a file) resource = proj.get_resource('path/to/your/file.py') # Create a refactoring object (e.g., Rename) refactoring = rename.Rename(proj, resource, 10, 'new_name') # 10 is the line number # Compute the changes changes = refactoring.get_changes() # Apply the changes proj.do(changes) # Close the project when done proj.close() ``` ### Response N/A (Library usage) ### Response Example N/A ``` -------------------------------- ### Configure Import Style Source: https://github.com/python-rope/rope/blob/master/docs/configuration.md Documentation for the preferred_import_style configuration option used to control how Rope generates import statements. ```APIDOC ## GET /config/imports/preferred_import_style ### Description Retrieves or defines the strategy used by Rope when inserting new import statements into the source code. ### Method GET/SET ### Endpoint /config/imports/preferred_import_style ### Parameters #### Request Body - **preferred_import_style** (str) - Required - The import style strategy. Options: "normal-import", "from-module", "from-global". ### Request Example { "preferred_import_style": "from-module" } ### Response #### Success Response (200) - **status** (string) - Confirmation of configuration update. #### Response Example { "status": "success", "current_style": "from-module" } ``` -------------------------------- ### Project Management Source: https://github.com/python-rope/rope/blob/master/docs/library.md Manage Rope projects, including creation, closing, and committing changes. ```APIDOC ## Project Creation and Management ### Creating a Project You can create a project by providing the root folder address. ```python project = Project(root_address) ``` ### `Project.close()` Closes a project's open resources. Always call this function when you don't need a project anymore. ```python myproject.close() ``` ### `Project.do()` Used to commit changes returned by refactorings. ```python project.do(changes) ``` ### `Project.history` A `rope.base.history.History` object. You can use its `undo` and `redo` methods for undoing or redoing changes. Note that you can use this only if you have committed your changes using rope. ``` -------------------------------- ### Rope Utility Functions (`rope.base.libutils`) Source: https://github.com/python-rope/rope/blob/master/docs/library.md A collection of utility functions in `rope.base.libutils` that simplify common tasks for building refactoring tools. ```APIDOC ## `rope.base.libutils` Functions The `rope.base.libutils` module contains functions that make life easier for building refactoring tools. In some cases, the functions offer a unified way to access or create objects. You’re encouraged to use `rope.base.libutils` functions whenever possible, because the APIs here may not be as volatile as class methods. ### `libutils.analyze_module()` Perform static object analysis on a Python file in the project. Note, this may be a very time consuming task. ```python libutils.analyze_module(myproject, resource) ``` ### `libutils.get_string_module()` Returns a `rope.base.pyobjects.PyModule` object for the code string. An optional `resource` argument can be specified for the resource this code is associated with. If `force_errors` is `True`, then `rope.base.exceptions.ModuleSyntaxError` is raised when the code has syntax errors. Otherwise, syntax errors are silently ignored. Note that `force_errors` overrides the `ignore_syntax_errors` project configuration flag. ```python pymodule = libutils.get_string_module(myproject, source) ``` ### `libutils.get_string_scope()` Get the `rope.base.pyscopes.GlobalScope` object for the code string. This is the outermost scope of the code encompassing the whole module. ```python scope = libutils.get_string_scope(myproject, source) ``` ### `libutils.is_python_file()` Returns `True` if the resource is a Python file. ```python libutils.is_python_file(myproject, resource) ``` ### `libutils.modname()` Retrieves the dotted path string to the module that contains that given resource. ```python # If resource is 'path/to/resource.py' relative to the project's root # directory, this returns the string: 'path.to.resource'. module_name = libutils.modname(resource) ``` ### `libutils.path_relative_to_project_root()` Retrieve the path relative to the project’s root directory. ```python # Get the path relative to the project's root directory. relpath = libutils.relative(myproject.address, path) ``` ### `libutils.path_to_resource()` Get the resource — a file or folder — at the given path. An optional `type` argument can be used if the resource doesn’t yet exist. The values for `type` are the strings `'file'` or `'folder'`. ```python # Resource for an existing file. myfile = libutils.path_to_resource(myproject, '/path/to/file.py') # Resource for a non-existing folder. new_folder = libutils.path_to_resource(myproject, '/path/to/folder', type='folder') ``` ``` -------------------------------- ### Run Rope Test Suite Source: https://github.com/python-rope/rope/blob/master/docs/contributing.md Execute the project's test suite using pytest. Ensure all tests pass before submitting changes. ```bash pytest -v ``` -------------------------------- ### Restructuring Function Calls to Operators Source: https://github.com/python-rope/rope/blob/master/docs/overview.md Demonstrates replacing custom power functions with the native Python '**' operator. It covers basic pattern matching and the use of wildcard arguments to ensure specific functions are targeted. ```python def pow(x, y): result = 1 for i in range(y): result *= x return result print(pow(2, 3)) ``` ```python def pow(x, y): result = 1 for i in range(y): result *= x return result print(2 ** 3) ``` -------------------------------- ### Guessing Function Return Values via Parameter Analysis Source: https://github.com/python-rope/rope/blob/master/docs/overview.md Demonstrates how Rope infers return types based on the input parameters passed to a function using conditional logic. ```python def func(arg): if isinstance(arg, C1): return C2() else: return C1() arg = mod1.C1() a_var = mod1.func(arg) ``` -------------------------------- ### Code Assist and Completions Source: https://context7.com/python-rope/rope/llms.txt Provides code completions, documentation lookup, and definition location for IDE integration. ```APIDOC ## Code Assist and Completions Get code completions, documentation, and definition locations for IDE integration. ```python from rope.base.project import Project from rope.base import libutils from rope.contrib import codeassist project = Project('/path/to/myproject') resource = libutils.path_to_resource(project, '/path/to/myproject/module.py') source_code = ''' import os class MyClass: def my_method(self): self.value = 42 obj = MyClass() obj.my_ ''' # Get completions at the cursor position (end of 'obj.my_') offset = len(source_code) - 1 proposals = codeassist.code_assist( project, source_code, offset, resource=resource, # Optional: for handling relative imports maxfixes=1, # Number of syntax errors to try fixing later_locals=True # Include names defined later in scope ) # Sort proposals by relevance sorted_proposals = codeassist.sorted_proposals(proposals) for proposal in sorted_proposals: print(f"Name: {proposal.name}") print(f"Type: {proposal.type}") # 'function', 'class', 'instance', 'module' print(f"Scope: {proposal.scope}") # 'local', 'global', 'builtin', 'attribute' print(f"Parameters: {proposal.parameters}") # For functions print(f"Doc: {proposal.get_doc()}") print("---") # Get the offset where completion should be inserted starting = codeassist.starting_offset(source_code, offset) # Insert like: source_code[:starting] + proposal.name + source_code[offset:] # Get documentation for a name doc = codeassist.get_doc(project, source_code, source_code.index('MyClass') + 1) print(f"Documentation: {doc}") # Get definition location location = codeassist.get_definition_location(project, source_code, source_code.index('my_method') + 1) resource, lineno = location print(f"Defined at: {resource.path if resource else 'same file'}, line {lineno}") # Get function call signature (calltip) calltip = codeassist.get_calltip(project, source_code, source_code.index('MyClass(') - 1) print(f"Calltip: {calltip}") project.close() ``` ``` -------------------------------- ### Extract Method and Variable Refactoring with Rope Source: https://context7.com/python-rope/rope/llms.txt Demonstrates how to use ExtractMethod and ExtractVariable to refactor code blocks into new methods or variables. It requires defining offsets within the source code and applying changes via the project object. ```python from rope.refactor.extract import ExtractMethod, ExtractVariable # Extract method start_offset = source.index('price = item') end_offset = source.index('total += subtotal') + len('total += subtotal') extractor = ExtractMethod(project, resource, start_offset, end_offset) changes = extractor.get_changes('calculate_item_subtotal', similar=True, global_=False) project.do(changes) # Extract variable start = source2.index('name.upper()') end = start + len('name.upper()') var_extractor = ExtractVariable(project, resource, start, end) changes = var_extractor.get_changes('upper_name', similar=True) project.do(changes) ``` -------------------------------- ### Configure Type Hinting Factory in Rope Source: https://github.com/python-rope/rope/blob/master/docs/configuration.md This snippet shows how to configure the type hinting factory within the Rope project preferences. It specifies the factory to be used for type hinting, which is crucial for code analysis and refactoring. ```python prefs[ "type_hinting_factory" ] = "rope.base.oi.type_hinting.factory.default_type_hinting_factory" ``` -------------------------------- ### IDE Integration Features Source: https://context7.com/python-rope/rope/llms.txt Details on how Rope can be used for IDE features like code completion, go-to-definition, and finding occurrences. ```APIDOC ## IDE Integration Features ### Description Provides examples of using Rope's components for common IDE functionalities. ### Method Illustrative Python code ### Endpoint N/A (Library usage) ### Parameters N/A ### Request Example ```python from rope.base import project from rope.codeassist import code_assist from rope.codeassist import get_definition_location from rope.codeassist import find_occurrences from rope.auto_import import AutoImport proj = project.Project('path/to/your/project') # Code completion assist_list = code_assist.CodeAssist(proj).get_completions('path/to/your/file.py', 10, 15) # line, column # Go to definition def_location = get_definition_location.get_definition_location(proj, 'path/to/your/file.py', 10, 15) # Find occurrences occurrences = find_occurrences.find_occurrences(proj, 'path/to/your/file.py', 10, 15) # Auto import auto_import = AutoImport(proj) # ... usage for import suggestions ... proj.close() ``` ### Response N/A (Library usage) ### Response Example N/A ``` -------------------------------- ### Inline Method Refactoring Source: https://github.com/python-rope/rope/blob/master/docs/overview.md Illustrates how to replace a method call with the method's body, including automatic import management and handling of classmethods. ```python class C(object): pass hello = 'Saying hello to %s from %s' % ('Rope', C.__name__) ``` -------------------------------- ### Refactoring Method Calls to Multiple Methods Source: https://github.com/python-rope/rope/blob/master/docs/overview.md Shows how to split a single method call into two separate method calls using pattern matching. This is useful for decomposing complex methods into smaller, more focused ones. ```python class A(object): def f(self, p1, p2): print(p1) print(p2) a = A() a.f(1, 2) ``` ```python class A(object): def f(self, p1, p2): print(p1) print(p2) def f1(self, p): print(p) def f2(self, p): print(p) a = A() a.f1(1) a.f2(2) ``` -------------------------------- ### Extract Method Refactoring Source: https://github.com/python-rope/rope/blob/master/docs/overview.md Demonstrates how to extract a selected expression or block of code into a new method. It also shows how to handle multi-line extractions and return multiple values. ```python def a_func(): a = 1 b = 2 * a c = new_func(a, b) def new_func(a, b): return a * 2 + b * 3 ``` -------------------------------- ### Define Type Hints using Epydoc Style Source: https://github.com/python-rope/rope/blob/master/docs/overview.md Shows the usage of Epydoc-style @type tags to provide type information to the Rope engine. ```python def myfunction(node): """Do something with a ``node``. @type node: ProgramNode """ node. ``` -------------------------------- ### Static Object Inference for Classes and Functions Source: https://github.com/python-rope/rope/blob/master/docs/overview.md Demonstrates how Rope infers object types and attributes through static analysis of class instances and function return values. ```python class AClass(object): def __init__(self): self.an_attr = 1 def call_a_func(self): return a_func() def a_func(): return AClass() a_var = a_func() another_var = a_var ``` -------------------------------- ### Moving Class Methods Source: https://github.com/python-rope/rope/blob/master/docs/overview.md Explains the process of moving a method to a class attribute and updating the original class to delegate calls to the new location. ```python class A(object): def new_method(self): pass class B(object): def __init__(self): self.attr = A() b = B() b.attr.new_method() ``` -------------------------------- ### Commit Changes with Rope Project Source: https://github.com/python-rope/rope/blob/master/docs/library.md This snippet shows how to use the `project.do()` method to commit changes that have been generated by refactoring operations. ```python project.do(changes) ``` -------------------------------- ### Static Object Analysis (SOA) Configuration Source: https://github.com/python-rope/rope/blob/master/docs/configuration.md Settings that control Rope's static object analysis, including its activation and depth. ```APIDOC ## Static Object Analysis (SOA) Configuration ### automatic_soa #### Description If set to `True`, Rope will analyze each module automatically when it is being saved. #### Type bool #### Default Value True ### soa_followed_calls #### Description Specifies the depth of function calls to follow during static object analysis. #### Type int #### Default Value 0 ``` -------------------------------- ### Moving Fields via Renaming Source: https://github.com/python-rope/rope/blob/master/docs/overview.md Demonstrates how to move a field to a different object by renaming the attribute to include the target object path. ```python class A(object): pass class B(object): def __init__(self): self.a = A() self.a.attr = 1 b = B() print(b.a.attr) ```