0
# Script Analysis
1
2
Core functionality for analyzing Python source code, providing completions, type inference, definition lookup, and navigation. The Script class is the main entry point for static code analysis with full project context support.
3
4
## Capabilities
5
6
### Script Creation
7
8
Initialize script analysis for source code with optional file path, environment, and project configuration.
9
10
```python { .api }
11
class Script:
12
def __init__(self, code=None, *, path=None, environment=None, project=None):
13
"""
14
Create a Script for code analysis.
15
16
Parameters:
17
- code (str, optional): Source code string. If None, reads from path.
18
- path (str or Path, optional): File path for the code.
19
- environment (Environment, optional): Python environment to use.
20
- project (Project, optional): Project configuration.
21
"""
22
```
23
24
**Usage Example:**
25
```python
26
import jedi
27
28
# Analyze code string
29
script = jedi.Script(code="import json\njson.loads", path="example.py")
30
31
# Analyze existing file
32
script = jedi.Script(path="/path/to/file.py")
33
34
# With custom environment and project
35
from jedi import Project
36
from jedi.api.environment import get_default_environment
37
38
project = Project("/path/to/project")
39
env = get_default_environment()
40
script = jedi.Script(code="import requests", project=project, environment=env)
41
```
42
43
### Code Completion
44
45
Get intelligent completions at a specific position in the code, supporting both normal and fuzzy matching.
46
47
```python { .api }
48
def complete(self, line=None, column=None, *, fuzzy=False):
49
"""
50
Get completions at cursor position.
51
52
Parameters:
53
- line (int, optional): Line number (1-based). Defaults to end of file.
54
- column (int, optional): Column number (0-based). Defaults to end of line.
55
- fuzzy (bool): Enable fuzzy matching. Default False.
56
57
Returns:
58
List of Completion objects sorted by name.
59
"""
60
```
61
62
**Usage Example:**
63
```python
64
code = '''
65
import json
66
json.lo'''
67
68
script = jedi.Script(code=code, path='example.py')
69
completions = script.complete(line=3, column=7) # At 'json.lo'
70
71
for completion in completions:
72
print(f"Name: {completion.name}")
73
print(f"Complete: {completion.complete}")
74
print(f"Type: {completion.type}")
75
print(f"Description: {completion.description}")
76
print("---")
77
78
# Fuzzy completion
79
completions = script.complete(line=3, column=7, fuzzy=True)
80
```
81
82
### Type Inference
83
84
Infer the type of expressions at a specific position, following complex paths through imports and statements.
85
86
```python { .api }
87
def infer(self, line=None, column=None, *, only_stubs=False, prefer_stubs=False):
88
"""
89
Infer types at cursor position.
90
91
Parameters:
92
- line (int, optional): Line number (1-based).
93
- column (int, optional): Column number (0-based).
94
- only_stubs (bool): Only return stub definitions. Default False.
95
- prefer_stubs (bool): Prefer stubs over Python objects. Default False.
96
97
Returns:
98
List of Name objects representing inferred types.
99
"""
100
```
101
102
**Usage Example:**
103
```python
104
code = '''
105
import json
106
data = json.loads('{"key": "value"}')
107
data.'''
108
109
script = jedi.Script(code=code, path='example.py')
110
definitions = script.infer(line=3, column=5) # At 'data.'
111
112
for definition in definitions:
113
print(f"Type: {definition.type}")
114
print(f"Full name: {definition.full_name}")
115
print(f"Module: {definition.module_name}")
116
print(f"Description: {definition.description}")
117
```
118
119
### Go to Definition
120
121
Navigate to the definition of symbols, with options for following imports and handling stubs.
122
123
```python { .api }
124
def goto(self, line=None, column=None, *, follow_imports=False,
125
follow_builtin_imports=False, only_stubs=False, prefer_stubs=False):
126
"""
127
Go to definition of symbol at cursor.
128
129
Parameters:
130
- line (int, optional): Line number (1-based).
131
- column (int, optional): Column number (0-based).
132
- follow_imports (bool): Follow import statements. Default False.
133
- follow_builtin_imports (bool): Follow builtin imports if follow_imports=True.
134
- only_stubs (bool): Only return stub definitions.
135
- prefer_stubs (bool): Prefer stubs over Python objects.
136
137
Returns:
138
List of Name objects representing definitions.
139
"""
140
```
141
142
**Usage Example:**
143
```python
144
code = '''
145
from collections import defaultdict
146
my_dict = defaultdict(list)
147
my_dict.append'''
148
149
script = jedi.Script(code=code, path='example.py')
150
151
# Basic goto
152
definitions = script.goto(line=3, column=8) # At 'my_dict'
153
154
# Follow imports to get actual implementation
155
definitions = script.goto(line=2, column=20, follow_imports=True) # At 'defaultdict'
156
157
for definition in definitions:
158
print(f"Name: {definition.name}")
159
print(f"File: {definition.module_path}")
160
print(f"Line: {definition.line}")
161
print(f"Type: {definition.type}")
162
```
163
164
### Function Signatures
165
166
Get function signatures showing parameters and their types for function calls.
167
168
```python { .api }
169
def get_signatures(self, line=None, column=None):
170
"""
171
Get function signatures at cursor position.
172
173
Parameters:
174
- line (int, optional): Line number (1-based).
175
- column (int, optional): Column number (0-based).
176
177
Returns:
178
List of Signature objects.
179
"""
180
```
181
182
**Usage Example:**
183
```python
184
code = '''
185
import json
186
json.loads('''
187
188
script = jedi.Script(code=code, path='example.py')
189
signatures = script.get_signatures(line=2, column=11) # Inside 'json.loads('
190
191
for signature in signatures:
192
print(f"Function: {signature.name}")
193
print(f"Current param index: {signature.index}")
194
print("Parameters:")
195
for param in signature.params:
196
print(f" {param.name}: {param.description}")
197
if param.infer_default():
198
defaults = param.infer_default()
199
print(f" Default: {defaults[0].name if defaults else 'None'}")
200
```
201
202
### Syntax Error Detection
203
204
Detect and report syntax errors in the analyzed code.
205
206
```python { .api }
207
def get_syntax_errors(self):
208
"""
209
Get syntax errors in the current code.
210
211
Returns:
212
List of SyntaxError objects.
213
"""
214
```
215
216
**Usage Example:**
217
```python
218
code = '''
219
def broken_function(
220
print("missing closing parenthesis")
221
'''
222
223
script = jedi.Script(code=code, path='example.py')
224
errors = script.get_syntax_errors()
225
226
for error in errors:
227
print(f"Error at line {error.line}, column {error.column}")
228
print(f"Message: {error.get_message()}")
229
if error.until_line:
230
print(f"Error spans to line {error.until_line}, column {error.until_column}")
231
```
232
233
### Name Extraction
234
235
Get all names defined in the current file with filtering options.
236
237
```python { .api }
238
def get_names(self, *, all_scopes=False, definitions=True, references=False):
239
"""
240
Get names defined in the current file.
241
242
Parameters:
243
- all_scopes (bool): Include names from all scopes, not just module level. Default False.
244
- definitions (bool): Include definition names (class, function, variable assignments). Default True.
245
- references (bool): Include reference names (variable usage). Default False.
246
247
Returns:
248
List of Name objects.
249
"""
250
```
251
252
**Usage Example:**
253
```python
254
code = '''
255
class MyClass:
256
def method(self, param):
257
local_var = param
258
return local_var
259
260
def function():
261
instance = MyClass()
262
return instance.method("test")
263
'''
264
265
script = jedi.Script(code=code, path='example.py')
266
267
# Get all definitions
268
definitions = script.get_names(definitions=True, references=False)
269
for name in definitions:
270
print(f"{name.type}: {name.name} at line {name.line}")
271
272
# Get all names including references
273
all_names = script.get_names(all_scopes=True, definitions=True, references=True)
274
```
275
276
### File-Level Search
277
278
Search for symbols within the current file being analyzed.
279
280
```python { .api }
281
def search(self, string, *, all_scopes=False):
282
"""
283
Search for names in the current file.
284
285
Parameters:
286
- string (str): Search string pattern.
287
- all_scopes (bool): Search in all scopes, not just module level. Default False.
288
289
Returns:
290
Generator of Name objects matching the search.
291
"""
292
293
def complete_search(self, string, *, all_scopes=False, fuzzy=False):
294
"""
295
Search with completion-style matching.
296
297
Parameters:
298
- string (str): Search string pattern.
299
- all_scopes (bool): Search in all scopes. Default False.
300
- fuzzy (bool): Enable fuzzy matching. Default False.
301
302
Returns:
303
Generator of Completion objects.
304
"""
305
```
306
307
**Usage Example:**
308
```python
309
code = '''
310
def calculate_sum(numbers):
311
total = 0
312
for num in numbers:
313
total += num
314
return total
315
316
def calculate_average(numbers):
317
return calculate_sum(numbers) / len(numbers)
318
'''
319
320
script = jedi.Script(code=code, path='example.py')
321
322
# Search for names containing 'calculate'
323
results = list(script.search('calculate'))
324
for result in results:
325
print(f"Found: {result.name} at line {result.line}")
326
327
# Fuzzy search
328
fuzzy_results = list(script.complete_search('calc', fuzzy=True))
329
for result in fuzzy_results:
330
print(f"Fuzzy match: {result.name}")
331
```
332
333
## Types
334
335
### Completion
336
337
```python { .api }
338
class Completion(BaseName):
339
complete: str # Rest of word to complete (None for fuzzy)
340
name_with_symbols: str # Name including symbols like 'param='
341
342
def get_completion_prefix_length(self):
343
"""Get length of prefix being completed."""
344
```
345
346
### SyntaxError
347
348
```python { .api }
349
class SyntaxError:
350
line: int # Error start line (1-based)
351
column: int # Error start column (0-based)
352
until_line: int # Error end line
353
until_column: int # Error end column
354
355
def get_message(self):
356
"""Get error message string."""
357
```