Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/jedi/api/__init__.py: 25%

299 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-03-26 06:07 +0000

1""" 

2The API basically only provides one class. You can create a :class:`Script` and 

3use its methods. 

4 

5Additionally you can add a debug function with :func:`set_debug_function`. 

6Alternatively, if you don't need a custom function and are happy with printing 

7debug messages to stdout, simply call :func:`set_debug_function` without 

8arguments. 

9""" 

10import sys 

11from pathlib import Path 

12 

13import parso 

14from parso.python import tree 

15 

16from jedi.parser_utils import get_executable_nodes 

17from jedi import debug 

18from jedi import settings 

19from jedi import cache 

20from jedi.file_io import KnownContentFileIO 

21from jedi.api import classes 

22from jedi.api import interpreter 

23from jedi.api import helpers 

24from jedi.api.helpers import validate_line_column 

25from jedi.api.completion import Completion, search_in_module 

26from jedi.api.keywords import KeywordName 

27from jedi.api.environment import InterpreterEnvironment 

28from jedi.api.project import get_default_project, Project 

29from jedi.api.errors import parso_to_jedi_errors 

30from jedi.api import refactoring 

31from jedi.api.refactoring.extract import extract_function, extract_variable 

32from jedi.inference import InferenceState 

33from jedi.inference import imports 

34from jedi.inference.references import find_references 

35from jedi.inference.arguments import try_iter_content 

36from jedi.inference.helpers import infer_call_of_leaf 

37from jedi.inference.sys_path import transform_path_to_dotted 

38from jedi.inference.syntax_tree import tree_name_to_values 

39from jedi.inference.value import ModuleValue 

40from jedi.inference.base_value import ValueSet 

41from jedi.inference.value.iterable import unpack_tuple_to_dict 

42from jedi.inference.gradual.conversion import convert_names, convert_values 

43from jedi.inference.gradual.utils import load_proper_stub_module 

44from jedi.inference.utils import to_list 

45 

46# Jedi uses lots and lots of recursion. By setting this a little bit higher, we 

47# can remove some "maximum recursion depth" errors. 

48sys.setrecursionlimit(3000) 

49 

50 

51class Script: 

52 """ 

53 A Script is the base for completions, goto or whatever you want to do with 

54 Jedi. The counter part of this class is :class:`Interpreter`, which works 

55 with actual dictionaries and can work with a REPL. This class 

56 should be used when a user edits code in an editor. 

57 

58 You can either use the ``code`` parameter or ``path`` to read a file. 

59 Usually you're going to want to use both of them (in an editor). 

60 

61 The Script's ``sys.path`` is very customizable: 

62 

63 - If `project` is provided with a ``sys_path``, that is going to be used. 

64 - If `environment` is provided, its ``sys.path`` will be used 

65 (see :func:`Environment.get_sys_path <jedi.api.environment.Environment.get_sys_path>`); 

66 - Otherwise ``sys.path`` will match that of the default environment of 

67 Jedi, which typically matches the sys path that was used at the time 

68 when Jedi was imported. 

69 

70 Most methods have a ``line`` and a ``column`` parameter. Lines in Jedi are 

71 always 1-based and columns are always zero based. To avoid repetition they 

72 are not always documented. You can omit both line and column. Jedi will 

73 then just do whatever action you are calling at the end of the file. If you 

74 provide only the line, just will complete at the end of that line. 

75 

76 .. warning:: By default :attr:`jedi.settings.fast_parser` is enabled, which means 

77 that parso reuses modules (i.e. they are not immutable). With this setting 

78 Jedi is **not thread safe** and it is also not safe to use multiple 

79 :class:`.Script` instances and its definitions at the same time. 

80 

81 If you are a normal plugin developer this should not be an issue. It is 

82 an issue for people that do more complex stuff with Jedi. 

83 

84 This is purely a performance optimization and works pretty well for all 

85 typical usages, however consider to turn the setting off if it causes 

86 you problems. See also 

87 `this discussion <https://github.com/davidhalter/jedi/issues/1240>`_. 

88 

89 :param code: The source code of the current file, separated by newlines. 

90 :type code: str 

91 :param path: The path of the file in the file system, or ``''`` if 

92 it hasn't been saved yet. 

93 :type path: str or pathlib.Path or None 

94 :param Environment environment: Provide a predefined :ref:`Environment <environments>` 

95 to work with a specific Python version or virtualenv. 

96 :param Project project: Provide a :class:`.Project` to make sure finding 

97 references works well, because the right folder is searched. There are 

98 also ways to modify the sys path and other things. 

99 """ 

100 def __init__(self, code=None, *, path=None, environment=None, project=None): 

101 self._orig_path = path 

102 if isinstance(path, str): 

103 path = Path(path) 

104 

105 self.path = path.absolute() if path else None 

106 

107 if code is None: 

108 if path is None: 

109 raise ValueError("Must provide at least one of code or path") 

110 

111 # TODO add a better warning than the traceback! 

112 with open(path, 'rb') as f: 

113 code = f.read() 

114 

115 if project is None: 

116 # Load the Python grammar of the current interpreter. 

117 project = get_default_project(None if self.path is None else self.path.parent) 

118 

119 self._inference_state = InferenceState( 

120 project, environment=environment, script_path=self.path 

121 ) 

122 debug.speed('init') 

123 self._module_node, code = self._inference_state.parse_and_get_code( 

124 code=code, 

125 path=self.path, 

126 use_latest_grammar=path and path.suffix == '.pyi', 

127 cache=False, # No disk cache, because the current script often changes. 

128 diff_cache=settings.fast_parser, 

129 cache_path=settings.cache_directory, 

130 ) 

131 debug.speed('parsed') 

132 self._code_lines = parso.split_lines(code, keepends=True) 

133 self._code = code 

134 

135 cache.clear_time_caches() 

136 debug.reset_time() 

137 

138 # Cache the module, this is mostly useful for testing, since this shouldn't 

139 # be called multiple times. 

140 @cache.memoize_method 

141 def _get_module(self): 

142 names = None 

143 is_package = False 

144 if self.path is not None: 

145 import_names, is_p = transform_path_to_dotted( 

146 self._inference_state.get_sys_path(add_parent_paths=False), 

147 self.path 

148 ) 

149 if import_names is not None: 

150 names = import_names 

151 is_package = is_p 

152 

153 if self.path is None: 

154 file_io = None 

155 else: 

156 file_io = KnownContentFileIO(self.path, self._code) 

157 if self.path is not None and self.path.suffix == '.pyi': 

158 # We are in a stub file. Try to load the stub properly. 

159 stub_module = load_proper_stub_module( 

160 self._inference_state, 

161 self._inference_state.latest_grammar, 

162 file_io, 

163 names, 

164 self._module_node 

165 ) 

166 if stub_module is not None: 

167 return stub_module 

168 

169 if names is None: 

170 names = ('__main__',) 

171 

172 module = ModuleValue( 

173 self._inference_state, self._module_node, 

174 file_io=file_io, 

175 string_names=names, 

176 code_lines=self._code_lines, 

177 is_package=is_package, 

178 ) 

179 if names[0] not in ('builtins', 'typing'): 

180 # These modules are essential for Jedi, so don't overwrite them. 

181 self._inference_state.module_cache.add(names, ValueSet([module])) 

182 return module 

183 

184 def _get_module_context(self): 

185 return self._get_module().as_context() 

186 

187 def __repr__(self): 

188 return '<%s: %s %r>' % ( 

189 self.__class__.__name__, 

190 repr(self._orig_path), 

191 self._inference_state.environment, 

192 ) 

193 

194 @validate_line_column 

195 def complete(self, line=None, column=None, *, fuzzy=False): 

196 """ 

197 Completes objects under the cursor. 

198 

199 Those objects contain information about the completions, more than just 

200 names. 

201 

202 :param fuzzy: Default False. Will return fuzzy completions, which means 

203 that e.g. ``ooa`` will match ``foobar``. 

204 :return: Completion objects, sorted by name. Normal names appear 

205 before "private" names that start with ``_`` and those appear 

206 before magic methods and name mangled names that start with ``__``. 

207 :rtype: list of :class:`.Completion` 

208 """ 

209 with debug.increase_indent_cm('complete'): 

210 completion = Completion( 

211 self._inference_state, self._get_module_context(), self._code_lines, 

212 (line, column), self.get_signatures, fuzzy=fuzzy, 

213 ) 

214 return completion.complete() 

215 

216 @validate_line_column 

217 def infer(self, line=None, column=None, *, only_stubs=False, prefer_stubs=False): 

218 """ 

219 Return the definitions of under the cursor. It is basically a wrapper 

220 around Jedi's type inference. 

221 

222 This method follows complicated paths and returns the end, not the 

223 first definition. The big difference between :meth:`goto` and 

224 :meth:`infer` is that :meth:`goto` doesn't 

225 follow imports and statements. Multiple objects may be returned, 

226 because depending on an option you can have two different versions of a 

227 function. 

228 

229 :param only_stubs: Only return stubs for this method. 

230 :param prefer_stubs: Prefer stubs to Python objects for this method. 

231 :rtype: list of :class:`.Name` 

232 """ 

233 pos = line, column 

234 leaf = self._module_node.get_name_of_position(pos) 

235 if leaf is None: 

236 leaf = self._module_node.get_leaf_for_position(pos) 

237 if leaf is None or leaf.type == 'string': 

238 return [] 

239 if leaf.end_pos == (line, column) and leaf.type == 'operator': 

240 next_ = leaf.get_next_leaf() 

241 if next_.start_pos == leaf.end_pos \ 

242 and next_.type in ('number', 'string', 'keyword'): 

243 leaf = next_ 

244 

245 context = self._get_module_context().create_context(leaf) 

246 

247 values = helpers.infer(self._inference_state, context, leaf) 

248 values = convert_values( 

249 values, 

250 only_stubs=only_stubs, 

251 prefer_stubs=prefer_stubs, 

252 ) 

253 

254 defs = [classes.Name(self._inference_state, c.name) for c in values] 

255 # The additional set here allows the definitions to become unique in an 

256 # API sense. In the internals we want to separate more things than in 

257 # the API. 

258 return helpers.sorted_definitions(set(defs)) 

259 

260 @validate_line_column 

261 def goto(self, line=None, column=None, *, follow_imports=False, follow_builtin_imports=False, 

262 only_stubs=False, prefer_stubs=False): 

263 """ 

264 Goes to the name that defined the object under the cursor. Optionally 

265 you can follow imports. 

266 Multiple objects may be returned, depending on an if you can have two 

267 different versions of a function. 

268 

269 :param follow_imports: The method will follow imports. 

270 :param follow_builtin_imports: If ``follow_imports`` is True will try 

271 to look up names in builtins (i.e. compiled or extension modules). 

272 :param only_stubs: Only return stubs for this method. 

273 :param prefer_stubs: Prefer stubs to Python objects for this method. 

274 :rtype: list of :class:`.Name` 

275 """ 

276 tree_name = self._module_node.get_name_of_position((line, column)) 

277 if tree_name is None: 

278 # Without a name we really just want to jump to the result e.g. 

279 # executed by `foo()`, if we the cursor is after `)`. 

280 return self.infer(line, column, only_stubs=only_stubs, prefer_stubs=prefer_stubs) 

281 name = self._get_module_context().create_name(tree_name) 

282 

283 # Make it possible to goto the super class function/attribute 

284 # definitions, when they are overwritten. 

285 names = [] 

286 if name.tree_name.is_definition() and name.parent_context.is_class(): 

287 class_node = name.parent_context.tree_node 

288 class_value = self._get_module_context().create_value(class_node) 

289 mro = class_value.py__mro__() 

290 next(mro) # Ignore the first entry, because it's the class itself. 

291 for cls in mro: 

292 names = cls.goto(tree_name.value) 

293 if names: 

294 break 

295 

296 if not names: 

297 names = list(name.goto()) 

298 

299 if follow_imports: 

300 names = helpers.filter_follow_imports(names, follow_builtin_imports) 

301 names = convert_names( 

302 names, 

303 only_stubs=only_stubs, 

304 prefer_stubs=prefer_stubs, 

305 ) 

306 

307 defs = [classes.Name(self._inference_state, d) for d in set(names)] 

308 # Avoid duplicates 

309 return list(set(helpers.sorted_definitions(defs))) 

310 

311 def search(self, string, *, all_scopes=False): 

312 """ 

313 Searches a name in the current file. For a description of how the 

314 search string should look like, please have a look at 

315 :meth:`.Project.search`. 

316 

317 :param bool all_scopes: Default False; searches not only for 

318 definitions on the top level of a module level, but also in 

319 functions and classes. 

320 :yields: :class:`.Name` 

321 """ 

322 return self._search_func(string, all_scopes=all_scopes) 

323 

324 @to_list 

325 def _search_func(self, string, all_scopes=False, complete=False, fuzzy=False): 

326 names = self._names(all_scopes=all_scopes) 

327 wanted_type, wanted_names = helpers.split_search_string(string) 

328 return search_in_module( 

329 self._inference_state, 

330 self._get_module_context(), 

331 names=names, 

332 wanted_type=wanted_type, 

333 wanted_names=wanted_names, 

334 complete=complete, 

335 fuzzy=fuzzy, 

336 ) 

337 

338 def complete_search(self, string, **kwargs): 

339 """ 

340 Like :meth:`.Script.search`, but completes that string. If you want to 

341 have all possible definitions in a file you can also provide an empty 

342 string. 

343 

344 :param bool all_scopes: Default False; searches not only for 

345 definitions on the top level of a module level, but also in 

346 functions and classes. 

347 :param fuzzy: Default False. Will return fuzzy completions, which means 

348 that e.g. ``ooa`` will match ``foobar``. 

349 :yields: :class:`.Completion` 

350 """ 

351 return self._search_func(string, complete=True, **kwargs) 

352 

353 @validate_line_column 

354 def help(self, line=None, column=None): 

355 """ 

356 Used to display a help window to users. Uses :meth:`.Script.goto` and 

357 returns additional definitions for keywords and operators. 

358 

359 Typically you will want to display :meth:`.BaseName.docstring` to the 

360 user for all the returned definitions. 

361 

362 The additional definitions are ``Name(...).type == 'keyword'``. 

363 These definitions do not have a lot of value apart from their docstring 

364 attribute, which contains the output of Python's :func:`help` function. 

365 

366 :rtype: list of :class:`.Name` 

367 """ 

368 definitions = self.goto(line, column, follow_imports=True) 

369 if definitions: 

370 return definitions 

371 leaf = self._module_node.get_leaf_for_position((line, column)) 

372 if leaf is not None and leaf.type in ('keyword', 'operator', 'error_leaf'): 

373 def need_pydoc(): 

374 if leaf.value in ('(', ')', '[', ']'): 

375 if leaf.parent.type == 'trailer': 

376 return False 

377 if leaf.parent.type == 'atom': 

378 return False 

379 grammar = self._inference_state.grammar 

380 # This parso stuff is not public, but since I control it, this 

381 # is fine :-) ~dave 

382 reserved = grammar._pgen_grammar.reserved_syntax_strings.keys() 

383 return leaf.value in reserved 

384 

385 if need_pydoc(): 

386 name = KeywordName(self._inference_state, leaf.value) 

387 return [classes.Name(self._inference_state, name)] 

388 return [] 

389 

390 @validate_line_column 

391 def get_references(self, line=None, column=None, **kwargs): 

392 """ 

393 Lists all references of a variable in a project. Since this can be 

394 quite hard to do for Jedi, if it is too complicated, Jedi will stop 

395 searching. 

396 

397 :param include_builtins: Default ``True``. If ``False``, checks if a definition 

398 is a builtin (e.g. ``sys``) and in that case does not return it. 

399 :param scope: Default ``'project'``. If ``'file'``, include references in 

400 the current module only. 

401 :rtype: list of :class:`.Name` 

402 """ 

403 

404 def _references(include_builtins=True, scope='project'): 

405 if scope not in ('project', 'file'): 

406 raise ValueError('Only the scopes "file" and "project" are allowed') 

407 tree_name = self._module_node.get_name_of_position((line, column)) 

408 if tree_name is None: 

409 # Must be syntax 

410 return [] 

411 

412 names = find_references(self._get_module_context(), tree_name, scope == 'file') 

413 

414 definitions = [classes.Name(self._inference_state, n) for n in names] 

415 if not include_builtins or scope == 'file': 

416 definitions = [d for d in definitions if not d.in_builtin_module()] 

417 return helpers.sorted_definitions(definitions) 

418 return _references(**kwargs) 

419 

420 @validate_line_column 

421 def get_signatures(self, line=None, column=None): 

422 """ 

423 Return the function object of the call under the cursor. 

424 

425 E.g. if the cursor is here:: 

426 

427 abs(# <-- cursor is here 

428 

429 This would return the ``abs`` function. On the other hand:: 

430 

431 abs()# <-- cursor is here 

432 

433 This would return an empty list.. 

434 

435 :rtype: list of :class:`.Signature` 

436 """ 

437 pos = line, column 

438 call_details = helpers.get_signature_details(self._module_node, pos) 

439 if call_details is None: 

440 return [] 

441 

442 context = self._get_module_context().create_context(call_details.bracket_leaf) 

443 definitions = helpers.cache_signatures( 

444 self._inference_state, 

445 context, 

446 call_details.bracket_leaf, 

447 self._code_lines, 

448 pos 

449 ) 

450 debug.speed('func_call followed') 

451 

452 # TODO here we use stubs instead of the actual values. We should use 

453 # the signatures from stubs, but the actual values, probably?! 

454 return [classes.Signature(self._inference_state, signature, call_details) 

455 for signature in definitions.get_signatures()] 

456 

457 @validate_line_column 

458 def get_context(self, line=None, column=None): 

459 """ 

460 Returns the scope context under the cursor. This basically means the 

461 function, class or module where the cursor is at. 

462 

463 :rtype: :class:`.Name` 

464 """ 

465 pos = (line, column) 

466 leaf = self._module_node.get_leaf_for_position(pos, include_prefixes=True) 

467 if leaf.start_pos > pos or leaf.type == 'endmarker': 

468 previous_leaf = leaf.get_previous_leaf() 

469 if previous_leaf is not None: 

470 leaf = previous_leaf 

471 

472 module_context = self._get_module_context() 

473 

474 n = tree.search_ancestor(leaf, 'funcdef', 'classdef') 

475 if n is not None and n.start_pos < pos <= n.children[-1].start_pos: 

476 # This is a bit of a special case. The context of a function/class 

477 # name/param/keyword is always it's parent context, not the 

478 # function itself. Catch all the cases here where we are before the 

479 # suite object, but still in the function. 

480 context = module_context.create_value(n).as_context() 

481 else: 

482 context = module_context.create_context(leaf) 

483 

484 while context.name is None: 

485 context = context.parent_context # comprehensions 

486 

487 definition = classes.Name(self._inference_state, context.name) 

488 while definition.type != 'module': 

489 name = definition._name # TODO private access 

490 tree_name = name.tree_name 

491 if tree_name is not None: # Happens with lambdas. 

492 scope = tree_name.get_definition() 

493 if scope.start_pos[1] < column: 

494 break 

495 definition = definition.parent() 

496 return definition 

497 

498 def _analysis(self): 

499 self._inference_state.is_analysis = True 

500 self._inference_state.analysis_modules = [self._module_node] 

501 module = self._get_module_context() 

502 try: 

503 for node in get_executable_nodes(self._module_node): 

504 context = module.create_context(node) 

505 if node.type in ('funcdef', 'classdef'): 

506 # Resolve the decorators. 

507 tree_name_to_values(self._inference_state, context, node.children[1]) 

508 elif isinstance(node, tree.Import): 

509 import_names = set(node.get_defined_names()) 

510 if node.is_nested(): 

511 import_names |= set(path[-1] for path in node.get_paths()) 

512 for n in import_names: 

513 imports.infer_import(context, n) 

514 elif node.type == 'expr_stmt': 

515 types = context.infer_node(node) 

516 for testlist in node.children[:-1:2]: 

517 # Iterate tuples. 

518 unpack_tuple_to_dict(context, types, testlist) 

519 else: 

520 if node.type == 'name': 

521 defs = self._inference_state.infer(context, node) 

522 else: 

523 defs = infer_call_of_leaf(context, node) 

524 try_iter_content(defs) 

525 self._inference_state.reset_recursion_limitations() 

526 

527 ana = [a for a in self._inference_state.analysis if self.path == a.path] 

528 return sorted(set(ana), key=lambda x: x.line) 

529 finally: 

530 self._inference_state.is_analysis = False 

531 

532 def get_names(self, **kwargs): 

533 """ 

534 Returns names defined in the current file. 

535 

536 :param all_scopes: If True lists the names of all scopes instead of 

537 only the module namespace. 

538 :param definitions: If True lists the names that have been defined by a 

539 class, function or a statement (``a = b`` returns ``a``). 

540 :param references: If True lists all the names that are not listed by 

541 ``definitions=True``. E.g. ``a = b`` returns ``b``. 

542 :rtype: list of :class:`.Name` 

543 """ 

544 names = self._names(**kwargs) 

545 return [classes.Name(self._inference_state, n) for n in names] 

546 

547 def get_syntax_errors(self): 

548 """ 

549 Lists all syntax errors in the current file. 

550 

551 :rtype: list of :class:`.SyntaxError` 

552 """ 

553 return parso_to_jedi_errors(self._inference_state.grammar, self._module_node) 

554 

555 def _names(self, all_scopes=False, definitions=True, references=False): 

556 # Set line/column to a random position, because they don't matter. 

557 module_context = self._get_module_context() 

558 defs = [ 

559 module_context.create_name(name) 

560 for name in helpers.get_module_names( 

561 self._module_node, 

562 all_scopes=all_scopes, 

563 definitions=definitions, 

564 references=references, 

565 ) 

566 ] 

567 return sorted(defs, key=lambda x: x.start_pos) 

568 

569 def rename(self, line=None, column=None, *, new_name): 

570 """ 

571 Renames all references of the variable under the cursor. 

572 

573 :param new_name: The variable under the cursor will be renamed to this 

574 string. 

575 :raises: :exc:`.RefactoringError` 

576 :rtype: :class:`.Refactoring` 

577 """ 

578 definitions = self.get_references(line, column, include_builtins=False) 

579 return refactoring.rename(self._inference_state, definitions, new_name) 

580 

581 @validate_line_column 

582 def extract_variable(self, line, column, *, new_name, until_line=None, until_column=None): 

583 """ 

584 Moves an expression to a new statement. 

585 

586 For example if you have the cursor on ``foo`` and provide a 

587 ``new_name`` called ``bar``:: 

588 

589 foo = 3.1 

590 x = int(foo + 1) 

591 

592 the code above will become:: 

593 

594 foo = 3.1 

595 bar = foo + 1 

596 x = int(bar) 

597 

598 :param new_name: The expression under the cursor will be renamed to 

599 this string. 

600 :param int until_line: The the selection range ends at this line, when 

601 omitted, Jedi will be clever and try to define the range itself. 

602 :param int until_column: The the selection range ends at this column, when 

603 omitted, Jedi will be clever and try to define the range itself. 

604 :raises: :exc:`.RefactoringError` 

605 :rtype: :class:`.Refactoring` 

606 """ 

607 if until_line is None and until_column is None: 

608 until_pos = None 

609 else: 

610 if until_line is None: 

611 until_line = line 

612 if until_column is None: 

613 until_column = len(self._code_lines[until_line - 1]) 

614 until_pos = until_line, until_column 

615 return extract_variable( 

616 self._inference_state, self.path, self._module_node, 

617 new_name, (line, column), until_pos 

618 ) 

619 

620 @validate_line_column 

621 def extract_function(self, line, column, *, new_name, until_line=None, until_column=None): 

622 """ 

623 Moves an expression to a new function. 

624 

625 For example if you have the cursor on ``foo`` and provide a 

626 ``new_name`` called ``bar``:: 

627 

628 global_var = 3 

629 

630 def x(): 

631 foo = 3.1 

632 x = int(foo + 1 + global_var) 

633 

634 the code above will become:: 

635 

636 global_var = 3 

637 

638 def bar(foo): 

639 return int(foo + 1 + global_var) 

640 

641 def x(): 

642 foo = 3.1 

643 x = bar(foo) 

644 

645 :param new_name: The expression under the cursor will be replaced with 

646 a function with this name. 

647 :param int until_line: The the selection range ends at this line, when 

648 omitted, Jedi will be clever and try to define the range itself. 

649 :param int until_column: The the selection range ends at this column, when 

650 omitted, Jedi will be clever and try to define the range itself. 

651 :raises: :exc:`.RefactoringError` 

652 :rtype: :class:`.Refactoring` 

653 """ 

654 if until_line is None and until_column is None: 

655 until_pos = None 

656 else: 

657 if until_line is None: 

658 until_line = line 

659 if until_column is None: 

660 until_column = len(self._code_lines[until_line - 1]) 

661 until_pos = until_line, until_column 

662 return extract_function( 

663 self._inference_state, self.path, self._get_module_context(), 

664 new_name, (line, column), until_pos 

665 ) 

666 

667 def inline(self, line=None, column=None): 

668 """ 

669 Inlines a variable under the cursor. This is basically the opposite of 

670 extracting a variable. For example with the cursor on bar:: 

671 

672 foo = 3.1 

673 bar = foo + 1 

674 x = int(bar) 

675 

676 the code above will become:: 

677 

678 foo = 3.1 

679 x = int(foo + 1) 

680 

681 :raises: :exc:`.RefactoringError` 

682 :rtype: :class:`.Refactoring` 

683 """ 

684 names = [d._name for d in self.get_references(line, column, include_builtins=True)] 

685 return refactoring.inline(self._inference_state, names) 

686 

687 

688class Interpreter(Script): 

689 """ 

690 Jedi's API for Python REPLs. 

691 

692 Implements all of the methods that are present in :class:`.Script` as well. 

693 

694 In addition to completions that normal REPL completion does like 

695 ``str.upper``, Jedi also supports code completion based on static code 

696 analysis. For example Jedi will complete ``str().upper``. 

697 

698 >>> from os.path import join 

699 >>> namespace = locals() 

700 >>> script = Interpreter('join("").up', [namespace]) 

701 >>> print(script.complete()[0].name) 

702 upper 

703 

704 All keyword arguments are same as the arguments for :class:`.Script`. 

705 

706 :param str code: Code to parse. 

707 :type namespaces: typing.List[dict] 

708 :param namespaces: A list of namespace dictionaries such as the one 

709 returned by :func:`globals` and :func:`locals`. 

710 """ 

711 _allow_descriptor_getattr_default = True 

712 

713 def __init__(self, code, namespaces, *, project=None, **kwds): 

714 try: 

715 namespaces = [dict(n) for n in namespaces] 

716 except Exception: 

717 raise TypeError("namespaces must be a non-empty list of dicts.") 

718 

719 environment = kwds.get('environment', None) 

720 if environment is None: 

721 environment = InterpreterEnvironment() 

722 else: 

723 if not isinstance(environment, InterpreterEnvironment): 

724 raise TypeError("The environment needs to be an InterpreterEnvironment subclass.") 

725 

726 if project is None: 

727 project = Project(Path.cwd()) 

728 

729 super().__init__(code, environment=environment, project=project, **kwds) 

730 

731 self.namespaces = namespaces 

732 self._inference_state.allow_descriptor_getattr = self._allow_descriptor_getattr_default 

733 

734 @cache.memoize_method 

735 def _get_module_context(self): 

736 if self.path is None: 

737 file_io = None 

738 else: 

739 file_io = KnownContentFileIO(self.path, self._code) 

740 tree_module_value = ModuleValue( 

741 self._inference_state, self._module_node, 

742 file_io=file_io, 

743 string_names=('__main__',), 

744 code_lines=self._code_lines, 

745 ) 

746 return interpreter.MixedModuleContext( 

747 tree_module_value, 

748 self.namespaces, 

749 ) 

750 

751 

752def preload_module(*modules): 

753 """ 

754 Preloading modules tells Jedi to load a module now, instead of lazy parsing 

755 of modules. This can be useful for IDEs, to control which modules to load 

756 on startup. 

757 

758 :param modules: different module names, list of string. 

759 """ 

760 for m in modules: 

761 s = "import %s as x; x." % m 

762 Script(s).complete(1, len(s)) 

763 

764 

765def set_debug_function(func_cb=debug.print_to_stdout, warnings=True, 

766 notices=True, speed=True): 

767 """ 

768 Define a callback debug function to get all the debug messages. 

769 

770 If you don't specify any arguments, debug messages will be printed to stdout. 

771 

772 :param func_cb: The callback function for debug messages. 

773 """ 

774 debug.debug_function = func_cb 

775 debug.enable_warning = warnings 

776 debug.enable_notice = notices 

777 debug.enable_speed = speed