A comprehensive Python refactoring library providing powerful and safe code transformations, analysis, and IDE integration capabilities.
—
IDE integration tools providing code completion, documentation lookup, definition finding, and occurrence detection. Designed for real-time assistance in development environments with comprehensive Python code analysis.
Intelligent code completion based on static analysis of Python code and project context.
def code_assist(project, source_code, offset, resource=None, templates=None, maxfixes=1, later_locals=True):
"""
Generate code completion proposals at the given offset.
Parameters:
- project (Project): Project instance for context
- source_code (str): Source code containing completion point
- offset (int): Character offset for completion
- resource (Resource, optional): File resource for better context
- templates (dict, optional): Custom code templates to include
- maxfixes (int): Maximum number of syntax fixes to attempt (default: 1)
- later_locals (bool): Include later-defined locals in scope (default: True)
Returns:
list[CompletionProposal]: List of completion proposals
"""
def sorted_proposals(proposals, scope, **kwargs):
"""
Sort completion proposals by relevance.
Parameters:
- proposals (list): List of completion proposals
- scope (str): Current scope for relevance ranking
- prefix (str, optional): Prefix being completed
Returns:
list[CompletionProposal]: Sorted proposals
"""
def starting_offset(source_code, offset):
"""
Get the starting offset of the identifier being completed.
Parameters:
- source_code (str): Source code
- offset (int): Current cursor position
Returns:
int: Starting offset of identifier
"""
def starting_expression(source_code, offset):
"""
Get the starting expression for completion context.
Parameters:
- source_code (str): Source code
- offset (int): Current cursor position
Returns:
str: Expression prefix for context
"""
class CompletionProposal:
"""
Code completion proposal.
Attributes:
- name (str): Identifier name
- display (str): Display string for UI
- insert (str): Text to insert
- kind (str): Proposal kind ('function', 'class', 'variable', etc.)
- scope (str): Scope information
- doc (str): Documentation string
"""
def __init__(self, name, kind, **kwargs): ...Retrieve documentation and function signatures for symbols.
def get_doc(project, source_code, offset, **kwargs):
"""
Get documentation for symbol at offset.
Parameters:
- project (Project): Project instance
- source_code (str): Source code containing symbol
- offset (int): Character offset of symbol
- resource (Resource, optional): File resource for context
- maxfixes (int): Maximum syntax fixes to attempt
Returns:
str: Documentation string or None if not found
"""
def get_calltip(project, source_code, offset, **kwargs):
"""
Get function call signature and documentation.
Parameters:
- project (Project): Project instance
- source_code (str): Source code containing call
- offset (int): Character offset within function call
- resource (Resource, optional): File resource for context
- ignore_unknown (bool): Ignore unknown parameters
Returns:
str: Call tip string with signature and documentation
"""Find definitions and navigate between code elements.
def get_definition_location(project, source_code, offset, **kwargs):
"""
Find definition location for symbol at offset.
Parameters:
- project (Project): Project instance
- source_code (str): Source code containing symbol
- offset (int): Character offset of symbol
- resource (Resource, optional): File resource for context
- maxfixes (int): Maximum syntax fixes to attempt
Returns:
tuple: (resource, line_number) or (None, None) if not found
"""
def find_occurrences(project, resource, offset, **kwargs):
"""
Find all occurrences of symbol at offset.
Parameters:
- project (Project): Project instance
- resource (Resource): File containing symbol
- offset (int): Character offset of symbol
- unsure (bool): Include uncertain occurrences
- in_hierarchy (bool): Search in class hierarchy
- docs (bool): Include documentation occurrences
Returns:
list[Location]: List of occurrence locations
"""
class Location:
"""
Location information for occurrences and definitions.
Attributes:
- resource (Resource): File resource
- offset (int): Character offset
- lineno (int): Line number (1-based)
"""
def __init__(self, resource, offset): ...Specialized find operations for comprehensive code navigation.
def find_implementations(project, resource, offset, **kwargs):
"""
Find implementations of abstract methods or interfaces.
Parameters:
- project (Project): Project instance
- resource (Resource): File containing abstract definition
- offset (int): Character offset of definition
Returns:
list[Location]: Implementation locations
"""
def find_definition(project, code, offset, **kwargs):
"""
Find definition for symbol in code string.
Parameters:
- project (Project): Project instance
- code (str): Source code
- offset (int): Character offset of symbol
- resource (Resource, optional): File context
Returns:
Location: Definition location or None
"""Code templates for common patterns and snippets.
def default_templates():
"""
Get default code templates.
Returns:
dict: Mapping of template names to Template objects
"""
class Template:
"""
Code template with placeholder substitution.
Attributes:
- name (str): Template name
- template (str): Template text with ${var} placeholders
- description (str): Template description
"""
def __init__(self, name, template, description=""): ...
def substitute(self, **kwargs):
"""
Substitute template variables.
Parameters:
- kwargs: Variable substitutions
Returns:
str: Expanded template text
"""
class TemplateProposal(CompletionProposal):
"""Completion proposal for code templates."""
def __init__(self, template, **kwargs): ...Automatic import statement generation and management.
class AutoImport:
"""
Auto-import functionality for missing symbols.
Parameters:
- project (Project): Project instance
- observe (bool): Observe project changes
- memory (bool): Use memory-based storage
"""
def __init__(self, project, observe=True, memory=False): ...
def generate_cache(self):
"""Generate import cache for all project modules."""
def get_import_statements(self, name, **kwargs):
"""
Get possible import statements for a name.
Parameters:
- name (str): Symbol name to import
- exact_match (bool): Require exact name match
Returns:
list[str]: Possible import statements
"""Find and report syntax and semantic errors in code.
def find_errors(project, resource):
"""
Find errors in a Python file.
Parameters:
- project (Project): Project instance
- resource (Resource): Python file to check
Returns:
list[Error]: List of detected errors
"""
class Error:
"""
Error information.
Attributes:
- resource (Resource): File containing error
- lineno (int): Line number of error
- message (str): Error message
- offset (int): Character offset of error
"""
def __init__(self, resource, lineno, message, offset=None): ...Generate code scaffolding and implementations.
def create_generate(project, code, resource, offset, **kwargs):
"""
Factory for code generators based on context at offset.
Parameters:
- project (Project): Project instance
- code (str): Source code
- resource (Resource): File resource
- offset (int): Character offset for generation context
Returns:
Generator instance appropriate for the context
"""
def create_module(project, name, sourcefolder=None):
"""
Create a new Python module.
Parameters:
- project (Project): Project instance
- name (str): Module name (dotted notation)
- sourcefolder (Resource, optional): Parent folder
Returns:
Resource: Created module file
"""
def create_package(project, name, sourcefolder=None):
"""
Create a new Python package.
Parameters:
- project (Project): Project instance
- name (str): Package name (dotted notation)
- sourcefolder (Resource, optional): Parent folder
Returns:
Resource: Created package folder
"""
class GenerateFunction:
"""Generate function implementations."""
def get_changes(self): ...
class GenerateVariable:
"""Generate variable assignments."""
def get_changes(self): ...
class GenerateClass:
"""Generate class definitions."""
def get_changes(self): ...from rope.base.project import Project
from rope.contrib.codeassist import code_assist, starting_offset
project = Project('/path/to/project')
try:
# Source code with completion point marked by cursor position
source = """
import sys
sys.pa| # completion at |
"""
offset = source.find('|')
source = source.replace('|', '')
# Get completion proposals
proposals = code_assist(project, source, offset)
# Print completions
for proposal in proposals:
print(f"{proposal.name} ({proposal.kind}): {proposal.display}")
finally:
project.close()from rope.base.project import Project
from rope.contrib.codeassist import get_definition_location
project = Project('/path/to/project')
try:
# Find definition of symbol at offset
myfile = project.get_resource('mymodule.py')
source = myfile.read()
# Find definition at character offset 250
resource, lineno = get_definition_location(
project, source, 250, resource=myfile
)
if resource:
print(f"Definition found in {resource.path} at line {lineno}")
else:
print("Definition not found")
finally:
project.close()from rope.base.project import Project
from rope.contrib.findit import find_occurrences
project = Project('/path/to/project')
try:
# Find all occurrences of symbol
myfile = project.get_resource('mymodule.py')
# Find occurrences at offset 300
locations = find_occurrences(project, myfile, 300, unsure=False)
print(f"Found {len(locations)} occurrences:")
for location in locations:
print(f" {location.resource.path}:{location.lineno}")
finally:
project.close()from rope.base.project import Project
from rope.contrib.autoimport import AutoImport
project = Project('/path/to/project')
try:
# Set up auto import
autoimport = AutoImport(project)
autoimport.generate_cache() # May take some time for large projects
# Get import suggestions for a symbol
imports = autoimport.get_import_statements('json')
print("Possible imports:")
for import_stmt in imports:
print(f" {import_stmt}")
finally:
project.close()from rope.base.project import Project
from rope.contrib.codeassist import get_doc, get_calltip
project = Project('/path/to/project')
try:
source = """
import json
json.loads(| # get calltip at |
"""
offset = source.find('|')
source = source.replace('|', '')
# Get function documentation
doc = get_doc(project, source, offset)
if doc:
print(f"Documentation: {doc}")
# Get call tip with signature
calltip = get_calltip(project, source, offset)
if calltip:
print(f"Call tip: {calltip}")
finally:
project.close()Install with Tessl CLI
npx tessl i tessl/pypi-rope