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"""
10from pathlib import Path
11from typing import Any
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, recursion_limit
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
47class Script:
48 """
49 A Script is the base for completions, goto or whatever you want to do with
50 Jedi. The counter part of this class is :class:`Interpreter`, which works
51 with actual dictionaries and can work with a REPL. This class
52 should be used when a user edits code in an editor.
53
54 You can either use the ``code`` parameter or ``path`` to read a file.
55 Usually you're going to want to use both of them (in an editor).
56
57 The Script's ``sys.path`` is very customizable:
58
59 - If `project` is provided with a ``sys_path``, that is going to be used.
60 - If `environment` is provided, its ``sys.path`` will be used
61 (see :func:`Environment.get_sys_path <jedi.api.environment.Environment.get_sys_path>`);
62 - Otherwise ``sys.path`` will match that of the default environment of
63 Jedi, which typically matches the sys path that was used at the time
64 when Jedi was imported.
65
66 Most methods have a ``line`` and a ``column`` parameter. Lines in Jedi are
67 always 1-based and columns are always zero based. To avoid repetition they
68 are not always documented. You can omit both line and column. Jedi will
69 then just do whatever action you are calling at the end of the file. If you
70 provide only the line, just will complete at the end of that line.
71
72 .. warning:: By default :attr:`jedi.settings.fast_parser` is enabled, which means
73 that parso reuses modules (i.e. they are not immutable). With this setting
74 Jedi is **not thread safe** and it is also not safe to use multiple
75 :class:`.Script` instances and its definitions at the same time.
76
77 If you are a normal plugin developer this should not be an issue. It is
78 an issue for people that do more complex stuff with Jedi.
79
80 This is purely a performance optimization and works pretty well for all
81 typical usages, however consider to turn the setting off if it causes
82 you problems. See also
83 `this discussion <https://github.com/davidhalter/jedi/issues/1240>`_.
84
85 :param code: The source code of the current file, separated by newlines.
86 :type code: str
87 :param path: The path of the file in the file system, or ``''`` if
88 it hasn't been saved yet.
89 :type path: str or pathlib.Path or None
90 :param Environment environment: Provide a predefined :ref:`Environment <environments>`
91 to work with a specific Python version or virtualenv.
92 :param Project project: Provide a :class:`.Project` to make sure finding
93 references works well, because the right folder is searched. There are
94 also ways to modify the sys path and other things.
95 """
96 @recursion_limit
97 def __init__(self, code=None, *, path=None, environment=None, project=None):
98 self._orig_path = path
99 if isinstance(path, str):
100 path = Path(path)
101
102 self.path = path.absolute() if path else None
103
104 if code is None:
105 if path is None:
106 raise ValueError("Must provide at least one of code or path")
107
108 # TODO add a better warning than the traceback!
109 with open(path, 'rb') as f:
110 code = f.read()
111
112 if project is None:
113 # Load the Python grammar of the current interpreter.
114 project = get_default_project(None if self.path is None else self.path.parent)
115
116 self._inference_state = InferenceState(
117 project, environment=environment, script_path=self.path
118 )
119 debug.speed('init')
120 self._module_node, code = self._inference_state.parse_and_get_code(
121 code=code,
122 path=self.path,
123 use_latest_grammar=path and path.suffix == '.pyi',
124 cache=False, # No disk cache, because the current script often changes.
125 diff_cache=settings.fast_parser,
126 cache_path=settings.cache_directory,
127 )
128 debug.speed('parsed')
129 self._code_lines = parso.split_lines(code, keepends=True)
130 self._code = code
131
132 cache.clear_time_caches()
133 debug.reset_time()
134
135 # Cache the module, this is mostly useful for testing, since this shouldn't
136 # be called multiple times.
137 @cache.memoize_method
138 def _get_module(self):
139 names = None
140 is_package = False
141 if self.path is not None:
142 import_names, is_p = transform_path_to_dotted(
143 self._inference_state.get_sys_path(add_parent_paths=False),
144 self.path
145 )
146 if import_names is not None:
147 names = import_names
148 is_package = is_p
149
150 if self.path is None:
151 file_io = None
152 else:
153 file_io = KnownContentFileIO(self.path, self._code)
154 if self.path is not None and self.path.suffix == '.pyi':
155 # We are in a stub file. Try to load the stub properly.
156 stub_module = load_proper_stub_module(
157 self._inference_state,
158 self._inference_state.latest_grammar,
159 file_io,
160 names,
161 self._module_node
162 )
163 if stub_module is not None:
164 return stub_module
165
166 if names is None:
167 names = ('__main__',)
168
169 module = ModuleValue(
170 self._inference_state, self._module_node,
171 file_io=file_io,
172 string_names=names,
173 code_lines=self._code_lines,
174 is_package=is_package,
175 )
176 if names[0] not in ('builtins', 'typing'):
177 # These modules are essential for Jedi, so don't overwrite them.
178 self._inference_state.module_cache.add(names, ValueSet([module]))
179 return module
180
181 def _get_module_context(self):
182 return self._get_module().as_context()
183
184 def __repr__(self):
185 return '<%s: %s %r>' % (
186 self.__class__.__name__,
187 repr(self._orig_path),
188 self._inference_state.environment,
189 )
190
191 @recursion_limit
192 @validate_line_column
193 def complete(self, line=None, column=None, *, fuzzy=False) -> list[classes.Completion]:
194 """
195 Completes objects under the cursor.
196
197 Those objects contain information about the completions, more than just
198 names.
199
200 :param fuzzy: Default False. Will return fuzzy completions, which means
201 that e.g. ``ooa`` will match ``foobar``.
202 :return: Completion objects, sorted by name. Normal names appear
203 before "private" names that start with ``_`` and those appear
204 before magic methods and name mangled names that start with ``__``.
205 :rtype: list of :class:`.Completion`
206 """
207 self._inference_state.reset_recursion_limitations()
208 with debug.increase_indent_cm('complete'):
209 completion = Completion(
210 self._inference_state, self._get_module_context(), self._code_lines,
211 (line, column), self.get_signatures, fuzzy=fuzzy,
212 )
213 return completion.complete()
214
215 @recursion_limit
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 self._inference_state.reset_recursion_limitations()
234 pos = line, column
235 leaf = self._module_node.get_name_of_position(pos)
236 if leaf is None:
237 leaf = self._module_node.get_leaf_for_position(pos)
238 if leaf is None or leaf.type == 'string':
239 return []
240 if leaf.end_pos == (line, column) and leaf.type == 'operator':
241 next_ = leaf.get_next_leaf()
242 if next_.start_pos == leaf.end_pos \
243 and next_.type in ('number', 'string', 'keyword'):
244 leaf = next_
245
246 context = self._get_module_context().create_context(leaf)
247
248 values = helpers.infer(self._inference_state, context, leaf)
249 values = convert_values(
250 values,
251 only_stubs=only_stubs,
252 prefer_stubs=prefer_stubs,
253 )
254
255 defs = [classes.Name(self._inference_state, c.name) for c in values]
256 # The additional set here allows the definitions to become unique in an
257 # API sense. In the internals we want to separate more things than in
258 # the API.
259 return helpers.sorted_definitions(set(defs))
260
261 @recursion_limit
262 @validate_line_column
263 def goto(self, line=None, column=None, *, follow_imports=False, follow_builtin_imports=False,
264 only_stubs=False, prefer_stubs=False):
265 """
266 Goes to the name that defined the object under the cursor. Optionally
267 you can follow imports.
268 Multiple objects may be returned, depending on an if you can have two
269 different versions of a function.
270
271 :param follow_imports: The method will follow imports.
272 :param follow_builtin_imports: If ``follow_imports`` is True will try
273 to look up names in builtins (i.e. compiled or extension modules).
274 :param only_stubs: Only return stubs for this method.
275 :param prefer_stubs: Prefer stubs to Python objects for this method.
276 :rtype: list of :class:`.Name`
277 """
278 self._inference_state.reset_recursion_limitations()
279 tree_name = self._module_node.get_name_of_position((line, column))
280 if tree_name is None:
281 # Without a name we really just want to jump to the result e.g.
282 # executed by `foo()`, if we the cursor is after `)`.
283 return self.infer(line, column, only_stubs=only_stubs, prefer_stubs=prefer_stubs)
284 name = self._get_module_context().create_name(tree_name)
285
286 # Make it possible to goto the super class function/attribute
287 # definitions, when they are overwritten.
288 names = []
289 if name.tree_name.is_definition() and name.parent_context.is_class():
290 class_node = name.parent_context.tree_node
291 class_value = self._get_module_context().create_value(class_node)
292 mro = class_value.py__mro__()
293 next(mro) # Ignore the first entry, because it's the class itself.
294 for cls in mro:
295 names = cls.goto(tree_name.value)
296 if names:
297 break
298
299 if not names:
300 names = list(name.goto())
301
302 if follow_imports:
303 names = helpers.filter_follow_imports(names, follow_builtin_imports)
304 names = convert_names(
305 names,
306 only_stubs=only_stubs,
307 prefer_stubs=prefer_stubs,
308 )
309
310 defs = [classes.Name(self._inference_state, d) for d in set(names)]
311 # Avoid duplicates
312 return list(set(helpers.sorted_definitions(defs)))
313
314 def search(self, string, *, all_scopes=False):
315 """
316 Searches a name in the current file. For a description of how the
317 search string should look like, please have a look at
318 :meth:`.Project.search`.
319
320 :param bool all_scopes: Default False; searches not only for
321 definitions on the top level of a module level, but also in
322 functions and classes.
323 :yields: :class:`.Name`
324 """
325 return self._search_func(string, all_scopes=all_scopes)
326
327 @recursion_limit
328 @to_list
329 def _search_func(self, string, all_scopes=False, complete=False, fuzzy=False):
330 names = self._names(all_scopes=all_scopes)
331 wanted_type, wanted_names = helpers.split_search_string(string)
332 return search_in_module(
333 self._inference_state,
334 self._get_module_context(),
335 names=names,
336 wanted_type=wanted_type,
337 wanted_names=wanted_names,
338 complete=complete,
339 fuzzy=fuzzy,
340 )
341
342 def complete_search(self, string, **kwargs) -> list[Any]:
343 """
344 Like :meth:`.Script.search`, but completes that string. If you want to
345 have all possible definitions in a file you can also provide an empty
346 string.
347
348 :param bool all_scopes: Default False; searches not only for
349 definitions on the top level of a module level, but also in
350 functions and classes.
351 :param fuzzy: Default False. Will return fuzzy completions, which means
352 that e.g. ``ooa`` will match ``foobar``.
353 :yields: :class:`.Completion`
354 """
355 return self._search_func(string, complete=True, **kwargs)
356
357 @recursion_limit
358 @validate_line_column
359 def help(self, line=None, column=None):
360 """
361 Used to display a help window to users. Uses :meth:`.Script.goto` and
362 returns additional definitions for keywords and operators.
363
364 Typically you will want to display :meth:`.BaseName.docstring` to the
365 user for all the returned definitions.
366
367 The additional definitions are ``Name(...).type == 'keyword'``.
368 These definitions do not have a lot of value apart from their docstring
369 attribute, which contains the output of Python's :func:`help` function.
370
371 :rtype: list of :class:`.Name`
372 """
373 self._inference_state.reset_recursion_limitations()
374 definitions = self.goto(line, column, follow_imports=True)
375 if definitions:
376 return definitions
377 leaf = self._module_node.get_leaf_for_position((line, column))
378
379 if leaf is not None and leaf.end_pos == (line, column) and leaf.type == 'newline':
380 next_ = leaf.get_next_leaf()
381 if next_ is not None and next_.start_pos == leaf.end_pos:
382 leaf = next_
383
384 if leaf is not None and leaf.type in ('keyword', 'operator', 'error_leaf'):
385 def need_pydoc():
386 if leaf.value in ('(', ')', '[', ']'):
387 if leaf.parent.type == 'trailer':
388 return False
389 if leaf.parent.type == 'atom':
390 return False
391 grammar = self._inference_state.grammar
392 # This parso stuff is not public, but since I control it, this
393 # is fine :-) ~dave
394 reserved = grammar._pgen_grammar.reserved_syntax_strings.keys()
395 return leaf.value in reserved
396
397 if need_pydoc():
398 name = KeywordName(self._inference_state, leaf.value)
399 return [classes.Name(self._inference_state, name)]
400 return []
401
402 @recursion_limit
403 @validate_line_column
404 def get_references(self, line=None, column=None, **kwargs):
405 """
406 Lists all references of a variable in a project. Since this can be
407 quite hard to do for Jedi, if it is too complicated, Jedi will stop
408 searching.
409
410 :param include_builtins: Default ``True``. If ``False``, checks if a definition
411 is a builtin (e.g. ``sys``) and in that case does not return it.
412 :param scope: Default ``'project'``. If ``'file'``, include references in
413 the current module only.
414 :rtype: list of :class:`.Name`
415 """
416 self._inference_state.reset_recursion_limitations()
417
418 def _references(include_builtins=True, scope='project'):
419 if scope not in ('project', 'file'):
420 raise ValueError('Only the scopes "file" and "project" are allowed')
421 tree_name = self._module_node.get_name_of_position((line, column))
422 if tree_name is None:
423 # Must be syntax
424 return []
425
426 names = find_references(self._get_module_context(), tree_name, scope == 'file')
427
428 definitions = [classes.Name(self._inference_state, n) for n in names]
429 if not include_builtins or scope == 'file':
430 definitions = [d for d in definitions if not d.in_builtin_module()]
431 return helpers.sorted_definitions(definitions)
432 return _references(**kwargs)
433
434 @recursion_limit
435 @validate_line_column
436 def get_signatures(self, line=None, column=None):
437 """
438 Return the function object of the call under the cursor.
439
440 E.g. if the cursor is here::
441
442 abs(# <-- cursor is here
443
444 This would return the ``abs`` function. On the other hand::
445
446 abs()# <-- cursor is here
447
448 This would return an empty list..
449
450 :rtype: list of :class:`.Signature`
451 """
452 self._inference_state.reset_recursion_limitations()
453 pos = line, column
454 call_details = helpers.get_signature_details(self._module_node, pos)
455 if call_details is None:
456 return []
457
458 context = self._get_module_context().create_context(call_details.bracket_leaf)
459 definitions = helpers.cache_signatures(
460 self._inference_state,
461 context,
462 call_details.bracket_leaf,
463 self._code_lines,
464 pos
465 )
466 debug.speed('func_call followed')
467
468 # TODO here we use stubs instead of the actual values. We should use
469 # the signatures from stubs, but the actual values, probably?!
470 return [classes.Signature(self._inference_state, signature, call_details)
471 for signature in definitions.get_signatures()]
472
473 @recursion_limit
474 @validate_line_column
475 def get_context(self, line=None, column=None):
476 """
477 Returns the scope context under the cursor. This basically means the
478 function, class or module where the cursor is at.
479
480 :rtype: :class:`.Name`
481 """
482 pos = (line, column)
483 leaf = self._module_node.get_leaf_for_position(pos, include_prefixes=True)
484 if leaf.start_pos > pos or leaf.type == 'endmarker':
485 previous_leaf = leaf.get_previous_leaf()
486 if previous_leaf is not None:
487 leaf = previous_leaf
488
489 module_context = self._get_module_context()
490
491 n = leaf.search_ancestor('funcdef', 'classdef')
492 if n is not None and n.start_pos < pos <= n.children[-1].start_pos:
493 # This is a bit of a special case. The context of a function/class
494 # name/param/keyword is always it's parent context, not the
495 # function itself. Catch all the cases here where we are before the
496 # suite object, but still in the function.
497 context = module_context.create_value(n).as_context()
498 else:
499 context = module_context.create_context(leaf)
500
501 while context.name is None:
502 context = context.parent_context # comprehensions
503
504 definition = classes.Name(self._inference_state, context.name)
505 while definition.type != 'module':
506 name = definition._name # TODO private access
507 tree_name = name.tree_name
508 if tree_name is not None: # Happens with lambdas.
509 scope = tree_name.get_definition()
510 if scope.parent.type in ('async_stmt', 'async_funcdef'):
511 scope = scope.parent
512 if scope.start_pos[1] < column:
513 break
514 definition = definition.parent()
515 return definition
516
517 def _analysis(self):
518 self._inference_state.is_analysis = True
519 self._inference_state.analysis_modules = [self._module_node]
520 module = self._get_module_context()
521 try:
522 for node in get_executable_nodes(self._module_node):
523 context = module.create_context(node)
524 if node.type in ('funcdef', 'classdef'):
525 # Resolve the decorators.
526 tree_name_to_values(self._inference_state, context, node.children[1])
527 elif isinstance(node, tree.Import):
528 import_names = set(node.get_defined_names())
529 if node.is_nested():
530 import_names |= set(path[-1] for path in node.get_paths())
531 for n in import_names:
532 imports.infer_import(context, n)
533 elif node.type == 'expr_stmt':
534 types = context.infer_node(node)
535 for testlist in node.children[:-1:2]:
536 # Iterate tuples.
537 unpack_tuple_to_dict(context, types, testlist)
538 else:
539 if node.type == 'name':
540 defs = self._inference_state.infer(context, node)
541 else:
542 defs = infer_call_of_leaf(context, node)
543 try_iter_content(defs)
544 self._inference_state.reset_recursion_limitations()
545
546 ana = [a for a in self._inference_state.analysis if self.path == a.path]
547 return sorted(set(ana), key=lambda x: x.line)
548 finally:
549 self._inference_state.is_analysis = False
550
551 @recursion_limit
552 def get_names(self, **kwargs):
553 """
554 Returns names defined in the current file.
555
556 :param all_scopes: If True lists the names of all scopes instead of
557 only the module namespace.
558 :param definitions: If True lists the names that have been defined by a
559 class, function or a statement (``a = b`` returns ``a``).
560 :param references: If True lists all the names that are not listed by
561 ``definitions=True``. E.g. ``a = b`` returns ``b``.
562 :rtype: list of :class:`.Name`
563 """
564 names = self._names(**kwargs)
565 return [classes.Name(self._inference_state, n) for n in names]
566
567 def get_syntax_errors(self):
568 """
569 Lists all syntax errors in the current file.
570
571 :rtype: list of :class:`.SyntaxError`
572 """
573 return parso_to_jedi_errors(self._inference_state.grammar, self._module_node)
574
575 def _names(self, all_scopes=False, definitions=True, references=False):
576 self._inference_state.reset_recursion_limitations()
577 # Set line/column to a random position, because they don't matter.
578 module_context = self._get_module_context()
579 defs = [
580 module_context.create_name(name)
581 for name in helpers.get_module_names(
582 self._module_node,
583 all_scopes=all_scopes,
584 definitions=definitions,
585 references=references,
586 )
587 ]
588 return sorted(defs, key=lambda x: x.start_pos)
589
590 @recursion_limit
591 def rename(self, line=None, column=None, *, new_name):
592 """
593 Renames all references of the variable under the cursor.
594
595 :param new_name: The variable under the cursor will be renamed to this
596 string.
597 :raises: :exc:`.RefactoringError`
598 :rtype: :class:`.Refactoring`
599 """
600 definitions = self.get_references(line, column, include_builtins=False)
601 return refactoring.rename(self._inference_state, definitions, new_name)
602
603 @recursion_limit
604 @validate_line_column
605 def extract_variable(self, line, column, *, new_name, until_line=None, until_column=None):
606 """
607 Moves an expression to a new statement.
608
609 For example if you have the cursor on ``foo`` and provide a
610 ``new_name`` called ``bar``::
611
612 foo = 3.1
613 x = int(foo + 1)
614
615 the code above will become::
616
617 foo = 3.1
618 bar = foo + 1
619 x = int(bar)
620
621 :param new_name: The expression under the cursor will be renamed to
622 this string.
623 :param int until_line: The the selection range ends at this line, when
624 omitted, Jedi will be clever and try to define the range itself.
625 :param int until_column: The the selection range ends at this column, when
626 omitted, Jedi will be clever and try to define the range itself.
627 :raises: :exc:`.RefactoringError`
628 :rtype: :class:`.Refactoring`
629 """
630 if until_line is None and until_column is None:
631 until_pos = None
632 else:
633 if until_line is None:
634 until_line = line
635 if until_column is None:
636 until_column = len(self._code_lines[until_line - 1])
637 until_pos = until_line, until_column
638 return extract_variable(
639 self._inference_state, self.path, self._module_node,
640 new_name, (line, column), until_pos
641 )
642
643 @recursion_limit
644 @validate_line_column
645 def extract_function(self, line, column, *, new_name, until_line=None, until_column=None):
646 """
647 Moves an expression to a new function.
648
649 For example if you have the cursor on ``foo`` and provide a
650 ``new_name`` called ``bar``::
651
652 global_var = 3
653
654 def x():
655 foo = 3.1
656 x = int(foo + 1 + global_var)
657
658 the code above will become::
659
660 global_var = 3
661
662 def bar(foo):
663 return int(foo + 1 + global_var)
664
665 def x():
666 foo = 3.1
667 x = bar(foo)
668
669 :param new_name: The expression under the cursor will be replaced with
670 a function with this name.
671 :param int until_line: The the selection range ends at this line, when
672 omitted, Jedi will be clever and try to define the range itself.
673 :param int until_column: The the selection range ends at this column, when
674 omitted, Jedi will be clever and try to define the range itself.
675 :raises: :exc:`.RefactoringError`
676 :rtype: :class:`.Refactoring`
677 """
678 if until_line is None and until_column is None:
679 until_pos = None
680 else:
681 if until_line is None:
682 until_line = line
683 if until_column is None:
684 until_column = len(self._code_lines[until_line - 1])
685 until_pos = until_line, until_column
686 return extract_function(
687 self._inference_state, self.path, self._get_module_context(),
688 new_name, (line, column), until_pos
689 )
690
691 @recursion_limit
692 def inline(self, line=None, column=None):
693 """
694 Inlines a variable under the cursor. This is basically the opposite of
695 extracting a variable. For example with the cursor on bar::
696
697 foo = 3.1
698 bar = foo + 1
699 x = int(bar)
700
701 the code above will become::
702
703 foo = 3.1
704 x = int(foo + 1)
705
706 :raises: :exc:`.RefactoringError`
707 :rtype: :class:`.Refactoring`
708 """
709 names = [d._name for d in self.get_references(line, column, include_builtins=True)]
710 return refactoring.inline(self._inference_state, names)
711
712
713class Interpreter(Script):
714 """
715 Jedi's API for Python REPLs.
716
717 Implements all of the methods that are present in :class:`.Script` as well.
718
719 In addition to completions that normal REPL completion does like
720 ``str.upper``, Jedi also supports code completion based on static code
721 analysis. For example Jedi will complete ``str().upper``.
722
723 >>> from os.path import join
724 >>> namespace = locals()
725 >>> script = Interpreter('join("").up', [namespace])
726 >>> print(script.complete()[0].name)
727 upper
728
729 All keyword arguments are same as the arguments for :class:`.Script`.
730
731 :param str code: Code to parse.
732 :type namespaces: typing.List[dict]
733 :param namespaces: A list of namespace dictionaries such as the one
734 returned by :func:`globals` and :func:`locals`.
735 """
736
737 def __init__(self, code, namespaces, *, project=None, **kwds):
738 try:
739 namespaces = [dict(n) for n in namespaces]
740 except Exception:
741 raise TypeError("namespaces must be a non-empty list of dicts.")
742
743 environment = kwds.get('environment', None)
744 if environment is None:
745 environment = InterpreterEnvironment()
746 else:
747 if not isinstance(environment, InterpreterEnvironment):
748 raise TypeError("The environment needs to be an InterpreterEnvironment subclass.")
749
750 if project is None:
751 project = Project(Path.cwd())
752
753 super().__init__(code, environment=environment, project=project, **kwds)
754
755 self.namespaces = namespaces
756 self._inference_state.allow_unsafe_executions = \
757 settings.allow_unsafe_interpreter_executions
758 # Dynamic params search is important when we work on functions that are
759 # called by other pieces of code. However for interpreter completions
760 # this is not important at all, because the current code is always new
761 # and will never be called by something.
762 # Also sometimes this logic goes a bit too far like in
763 # https://github.com/ipython/ipython/issues/13866, where it takes
764 # seconds to do a simple completion.
765 self._inference_state.do_dynamic_params_search = False
766
767 @cache.memoize_method
768 def _get_module_context(self):
769 if self.path is None:
770 file_io = None
771 else:
772 file_io = KnownContentFileIO(self.path, self._code)
773 tree_module_value = ModuleValue(
774 self._inference_state, self._module_node,
775 file_io=file_io,
776 string_names=('__main__',),
777 code_lines=self._code_lines,
778 )
779 return interpreter.MixedModuleContext(
780 tree_module_value,
781 self.namespaces,
782 )
783
784
785def preload_module(*modules):
786 """
787 Preloading modules tells Jedi to load a module now, instead of lazy parsing
788 of modules. This can be useful for IDEs, to control which modules to load
789 on startup.
790
791 :param modules: different module names, list of string.
792 """
793 for m in modules:
794 Script(f"import {m}").infer()
795
796
797def set_debug_function(func_cb=debug.print_to_stdout, warnings=True,
798 notices=True, speed=True):
799 """
800 Define a callback debug function to get all the debug messages.
801
802 If you don't specify any arguments, debug messages will be printed to stdout.
803
804 :param func_cb: The callback function for debug messages.
805 """
806 debug.debug_function = func_cb
807 debug.enable_warning = warnings
808 debug.enable_notice = notices
809 debug.enable_speed = speed