0
# Code Assistance
1
2
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.
3
4
## Capabilities
5
6
### Code Completion
7
8
Intelligent code completion based on static analysis of Python code and project context.
9
10
```python { .api }
11
def code_assist(project, source_code, offset, resource=None, templates=None, maxfixes=1, later_locals=True):
12
"""
13
Generate code completion proposals at the given offset.
14
15
Parameters:
16
- project (Project): Project instance for context
17
- source_code (str): Source code containing completion point
18
- offset (int): Character offset for completion
19
- resource (Resource, optional): File resource for better context
20
- templates (dict, optional): Custom code templates to include
21
- maxfixes (int): Maximum number of syntax fixes to attempt (default: 1)
22
- later_locals (bool): Include later-defined locals in scope (default: True)
23
24
Returns:
25
list[CompletionProposal]: List of completion proposals
26
"""
27
28
def sorted_proposals(proposals, scope, **kwargs):
29
"""
30
Sort completion proposals by relevance.
31
32
Parameters:
33
- proposals (list): List of completion proposals
34
- scope (str): Current scope for relevance ranking
35
- prefix (str, optional): Prefix being completed
36
37
Returns:
38
list[CompletionProposal]: Sorted proposals
39
"""
40
41
def starting_offset(source_code, offset):
42
"""
43
Get the starting offset of the identifier being completed.
44
45
Parameters:
46
- source_code (str): Source code
47
- offset (int): Current cursor position
48
49
Returns:
50
int: Starting offset of identifier
51
"""
52
53
def starting_expression(source_code, offset):
54
"""
55
Get the starting expression for completion context.
56
57
Parameters:
58
- source_code (str): Source code
59
- offset (int): Current cursor position
60
61
Returns:
62
str: Expression prefix for context
63
"""
64
65
class CompletionProposal:
66
"""
67
Code completion proposal.
68
69
Attributes:
70
- name (str): Identifier name
71
- display (str): Display string for UI
72
- insert (str): Text to insert
73
- kind (str): Proposal kind ('function', 'class', 'variable', etc.)
74
- scope (str): Scope information
75
- doc (str): Documentation string
76
"""
77
78
def __init__(self, name, kind, **kwargs): ...
79
```
80
81
### Documentation and Call Tips
82
83
Retrieve documentation and function signatures for symbols.
84
85
```python { .api }
86
def get_doc(project, source_code, offset, **kwargs):
87
"""
88
Get documentation for symbol at offset.
89
90
Parameters:
91
- project (Project): Project instance
92
- source_code (str): Source code containing symbol
93
- offset (int): Character offset of symbol
94
- resource (Resource, optional): File resource for context
95
- maxfixes (int): Maximum syntax fixes to attempt
96
97
Returns:
98
str: Documentation string or None if not found
99
"""
100
101
def get_calltip(project, source_code, offset, **kwargs):
102
"""
103
Get function call signature and documentation.
104
105
Parameters:
106
- project (Project): Project instance
107
- source_code (str): Source code containing call
108
- offset (int): Character offset within function call
109
- resource (Resource, optional): File resource for context
110
- ignore_unknown (bool): Ignore unknown parameters
111
112
Returns:
113
str: Call tip string with signature and documentation
114
"""
115
```
116
117
### Definition and Navigation
118
119
Find definitions and navigate between code elements.
120
121
```python { .api }
122
def get_definition_location(project, source_code, offset, **kwargs):
123
"""
124
Find definition location for symbol at offset.
125
126
Parameters:
127
- project (Project): Project instance
128
- source_code (str): Source code containing symbol
129
- offset (int): Character offset of symbol
130
- resource (Resource, optional): File resource for context
131
- maxfixes (int): Maximum syntax fixes to attempt
132
133
Returns:
134
tuple: (resource, line_number) or (None, None) if not found
135
"""
136
137
def find_occurrences(project, resource, offset, **kwargs):
138
"""
139
Find all occurrences of symbol at offset.
140
141
Parameters:
142
- project (Project): Project instance
143
- resource (Resource): File containing symbol
144
- offset (int): Character offset of symbol
145
- unsure (bool): Include uncertain occurrences
146
- in_hierarchy (bool): Search in class hierarchy
147
- docs (bool): Include documentation occurrences
148
149
Returns:
150
list[Location]: List of occurrence locations
151
"""
152
153
class Location:
154
"""
155
Location information for occurrences and definitions.
156
157
Attributes:
158
- resource (Resource): File resource
159
- offset (int): Character offset
160
- lineno (int): Line number (1-based)
161
"""
162
163
def __init__(self, resource, offset): ...
164
```
165
166
### Advanced Find Operations
167
168
Specialized find operations for comprehensive code navigation.
169
170
```python { .api }
171
def find_implementations(project, resource, offset, **kwargs):
172
"""
173
Find implementations of abstract methods or interfaces.
174
175
Parameters:
176
- project (Project): Project instance
177
- resource (Resource): File containing abstract definition
178
- offset (int): Character offset of definition
179
180
Returns:
181
list[Location]: Implementation locations
182
"""
183
184
def find_definition(project, code, offset, **kwargs):
185
"""
186
Find definition for symbol in code string.
187
188
Parameters:
189
- project (Project): Project instance
190
- code (str): Source code
191
- offset (int): Character offset of symbol
192
- resource (Resource, optional): File context
193
194
Returns:
195
Location: Definition location or None
196
"""
197
```
198
199
### Template System
200
201
Code templates for common patterns and snippets.
202
203
```python { .api }
204
def default_templates():
205
"""
206
Get default code templates.
207
208
Returns:
209
dict: Mapping of template names to Template objects
210
"""
211
212
class Template:
213
"""
214
Code template with placeholder substitution.
215
216
Attributes:
217
- name (str): Template name
218
- template (str): Template text with ${var} placeholders
219
- description (str): Template description
220
"""
221
222
def __init__(self, name, template, description=""): ...
223
224
def substitute(self, **kwargs):
225
"""
226
Substitute template variables.
227
228
Parameters:
229
- kwargs: Variable substitutions
230
231
Returns:
232
str: Expanded template text
233
"""
234
235
class TemplateProposal(CompletionProposal):
236
"""Completion proposal for code templates."""
237
238
def __init__(self, template, **kwargs): ...
239
```
240
241
### Auto Import
242
243
Automatic import statement generation and management.
244
245
```python { .api }
246
class AutoImport:
247
"""
248
Auto-import functionality for missing symbols.
249
250
Parameters:
251
- project (Project): Project instance
252
- observe (bool): Observe project changes
253
- memory (bool): Use memory-based storage
254
"""
255
def __init__(self, project, observe=True, memory=False): ...
256
257
def generate_cache(self):
258
"""Generate import cache for all project modules."""
259
260
def get_import_statements(self, name, **kwargs):
261
"""
262
Get possible import statements for a name.
263
264
Parameters:
265
- name (str): Symbol name to import
266
- exact_match (bool): Require exact name match
267
268
Returns:
269
list[str]: Possible import statements
270
"""
271
```
272
273
### Error Detection
274
275
Find and report syntax and semantic errors in code.
276
277
```python { .api }
278
def find_errors(project, resource):
279
"""
280
Find errors in a Python file.
281
282
Parameters:
283
- project (Project): Project instance
284
- resource (Resource): Python file to check
285
286
Returns:
287
list[Error]: List of detected errors
288
"""
289
290
class Error:
291
"""
292
Error information.
293
294
Attributes:
295
- resource (Resource): File containing error
296
- lineno (int): Line number of error
297
- message (str): Error message
298
- offset (int): Character offset of error
299
"""
300
301
def __init__(self, resource, lineno, message, offset=None): ...
302
```
303
304
### Code Generation
305
306
Generate code scaffolding and implementations.
307
308
```python { .api }
309
def create_generate(project, code, resource, offset, **kwargs):
310
"""
311
Factory for code generators based on context at offset.
312
313
Parameters:
314
- project (Project): Project instance
315
- code (str): Source code
316
- resource (Resource): File resource
317
- offset (int): Character offset for generation context
318
319
Returns:
320
Generator instance appropriate for the context
321
"""
322
323
def create_module(project, name, sourcefolder=None):
324
"""
325
Create a new Python module.
326
327
Parameters:
328
- project (Project): Project instance
329
- name (str): Module name (dotted notation)
330
- sourcefolder (Resource, optional): Parent folder
331
332
Returns:
333
Resource: Created module file
334
"""
335
336
def create_package(project, name, sourcefolder=None):
337
"""
338
Create a new Python package.
339
340
Parameters:
341
- project (Project): Project instance
342
- name (str): Package name (dotted notation)
343
- sourcefolder (Resource, optional): Parent folder
344
345
Returns:
346
Resource: Created package folder
347
"""
348
349
class GenerateFunction:
350
"""Generate function implementations."""
351
def get_changes(self): ...
352
353
class GenerateVariable:
354
"""Generate variable assignments."""
355
def get_changes(self): ...
356
357
class GenerateClass:
358
"""Generate class definitions."""
359
def get_changes(self): ...
360
```
361
362
## Usage Examples
363
364
### Code Completion
365
366
```python
367
from rope.base.project import Project
368
from rope.contrib.codeassist import code_assist, starting_offset
369
370
project = Project('/path/to/project')
371
372
try:
373
# Source code with completion point marked by cursor position
374
source = """
375
import sys
376
sys.pa| # completion at |
377
"""
378
offset = source.find('|')
379
source = source.replace('|', '')
380
381
# Get completion proposals
382
proposals = code_assist(project, source, offset)
383
384
# Print completions
385
for proposal in proposals:
386
print(f"{proposal.name} ({proposal.kind}): {proposal.display}")
387
388
finally:
389
project.close()
390
```
391
392
### Find Definition
393
394
```python
395
from rope.base.project import Project
396
from rope.contrib.codeassist import get_definition_location
397
398
project = Project('/path/to/project')
399
400
try:
401
# Find definition of symbol at offset
402
myfile = project.get_resource('mymodule.py')
403
source = myfile.read()
404
405
# Find definition at character offset 250
406
resource, lineno = get_definition_location(
407
project, source, 250, resource=myfile
408
)
409
410
if resource:
411
print(f"Definition found in {resource.path} at line {lineno}")
412
else:
413
print("Definition not found")
414
415
finally:
416
project.close()
417
```
418
419
### Find All Occurrences
420
421
```python
422
from rope.base.project import Project
423
from rope.contrib.findit import find_occurrences
424
425
project = Project('/path/to/project')
426
427
try:
428
# Find all occurrences of symbol
429
myfile = project.get_resource('mymodule.py')
430
431
# Find occurrences at offset 300
432
locations = find_occurrences(project, myfile, 300, unsure=False)
433
434
print(f"Found {len(locations)} occurrences:")
435
for location in locations:
436
print(f" {location.resource.path}:{location.lineno}")
437
438
finally:
439
project.close()
440
```
441
442
### Auto Import
443
444
```python
445
from rope.base.project import Project
446
from rope.contrib.autoimport import AutoImport
447
448
project = Project('/path/to/project')
449
450
try:
451
# Set up auto import
452
autoimport = AutoImport(project)
453
autoimport.generate_cache() # May take some time for large projects
454
455
# Get import suggestions for a symbol
456
imports = autoimport.get_import_statements('json')
457
458
print("Possible imports:")
459
for import_stmt in imports:
460
print(f" {import_stmt}")
461
462
finally:
463
project.close()
464
```
465
466
### Get Documentation
467
468
```python
469
from rope.base.project import Project
470
from rope.contrib.codeassist import get_doc, get_calltip
471
472
project = Project('/path/to/project')
473
474
try:
475
source = """
476
import json
477
json.loads(| # get calltip at |
478
"""
479
offset = source.find('|')
480
source = source.replace('|', '')
481
482
# Get function documentation
483
doc = get_doc(project, source, offset)
484
if doc:
485
print(f"Documentation: {doc}")
486
487
# Get call tip with signature
488
calltip = get_calltip(project, source, offset)
489
if calltip:
490
print(f"Call tip: {calltip}")
491
492
finally:
493
project.close()
494
```