Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/jedi/api/__init__.py: 24%
310 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
1"""
2The API basically only provides one class. You can create a :class:`Script` and
3use its methods.
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
13import parso
14from parso.python import tree
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
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)
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.
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).
61 The Script's ``sys.path`` is very customizable:
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.
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.
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.
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.
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>`_.
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)
105 self.path = path.absolute() if path else None
107 if code is None:
108 if path is None:
109 raise ValueError("Must provide at least one of code or path")
111 # TODO add a better warning than the traceback!
112 with open(path, 'rb') as f:
113 code = f.read()
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)
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
135 cache.clear_time_caches()
136 debug.reset_time()
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
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
169 if names is None:
170 names = ('__main__',)
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
184 def _get_module_context(self):
185 return self._get_module().as_context()
187 def __repr__(self):
188 return '<%s: %s %r>' % (
189 self.__class__.__name__,
190 repr(self._orig_path),
191 self._inference_state.environment,
192 )
194 @validate_line_column
195 def complete(self, line=None, column=None, *, fuzzy=False):
196 """
197 Completes objects under the cursor.
199 Those objects contain information about the completions, more than just
200 names.
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 self._inference_state.reset_recursion_limitations()
210 with debug.increase_indent_cm('complete'):
211 completion = Completion(
212 self._inference_state, self._get_module_context(), self._code_lines,
213 (line, column), self.get_signatures, fuzzy=fuzzy,
214 )
215 return completion.complete()
217 @validate_line_column
218 def infer(self, line=None, column=None, *, only_stubs=False, prefer_stubs=False):
219 self._inference_state.reset_recursion_limitations()
220 """
221 Return the definitions of under the cursor. It is basically a wrapper
222 around Jedi's type inference.
224 This method follows complicated paths and returns the end, not the
225 first definition. The big difference between :meth:`goto` and
226 :meth:`infer` is that :meth:`goto` doesn't
227 follow imports and statements. Multiple objects may be returned,
228 because depending on an option you can have two different versions of a
229 function.
231 :param only_stubs: Only return stubs for this method.
232 :param prefer_stubs: Prefer stubs to Python objects for this method.
233 :rtype: list of :class:`.Name`
234 """
235 pos = line, column
236 leaf = self._module_node.get_name_of_position(pos)
237 if leaf is None:
238 leaf = self._module_node.get_leaf_for_position(pos)
239 if leaf is None or leaf.type == 'string':
240 return []
241 if leaf.end_pos == (line, column) and leaf.type == 'operator':
242 next_ = leaf.get_next_leaf()
243 if next_.start_pos == leaf.end_pos \
244 and next_.type in ('number', 'string', 'keyword'):
245 leaf = next_
247 context = self._get_module_context().create_context(leaf)
249 values = helpers.infer(self._inference_state, context, leaf)
250 values = convert_values(
251 values,
252 only_stubs=only_stubs,
253 prefer_stubs=prefer_stubs,
254 )
256 defs = [classes.Name(self._inference_state, c.name) for c in values]
257 # The additional set here allows the definitions to become unique in an
258 # API sense. In the internals we want to separate more things than in
259 # the API.
260 return helpers.sorted_definitions(set(defs))
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 self._inference_state.reset_recursion_limitations()
266 """
267 Goes to the name that defined the object under the cursor. Optionally
268 you can follow imports.
269 Multiple objects may be returned, depending on an if you can have two
270 different versions of a function.
272 :param follow_imports: The method will follow imports.
273 :param follow_builtin_imports: If ``follow_imports`` is True will try
274 to look up names in builtins (i.e. compiled or extension modules).
275 :param only_stubs: Only return stubs for this method.
276 :param prefer_stubs: Prefer stubs to Python objects for this method.
277 :rtype: list of :class:`.Name`
278 """
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)
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
299 if not names:
300 names = list(name.goto())
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 )
310 defs = [classes.Name(self._inference_state, d) for d in set(names)]
311 # Avoid duplicates
312 return list(set(helpers.sorted_definitions(defs)))
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`.
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)
327 @to_list
328 def _search_func(self, string, all_scopes=False, complete=False, fuzzy=False):
329 names = self._names(all_scopes=all_scopes)
330 wanted_type, wanted_names = helpers.split_search_string(string)
331 return search_in_module(
332 self._inference_state,
333 self._get_module_context(),
334 names=names,
335 wanted_type=wanted_type,
336 wanted_names=wanted_names,
337 complete=complete,
338 fuzzy=fuzzy,
339 )
341 def complete_search(self, string, **kwargs):
342 """
343 Like :meth:`.Script.search`, but completes that string. If you want to
344 have all possible definitions in a file you can also provide an empty
345 string.
347 :param bool all_scopes: Default False; searches not only for
348 definitions on the top level of a module level, but also in
349 functions and classes.
350 :param fuzzy: Default False. Will return fuzzy completions, which means
351 that e.g. ``ooa`` will match ``foobar``.
352 :yields: :class:`.Completion`
353 """
354 return self._search_func(string, complete=True, **kwargs)
356 @validate_line_column
357 def help(self, line=None, column=None):
358 """
359 Used to display a help window to users. Uses :meth:`.Script.goto` and
360 returns additional definitions for keywords and operators.
362 Typically you will want to display :meth:`.BaseName.docstring` to the
363 user for all the returned definitions.
365 The additional definitions are ``Name(...).type == 'keyword'``.
366 These definitions do not have a lot of value apart from their docstring
367 attribute, which contains the output of Python's :func:`help` function.
369 :rtype: list of :class:`.Name`
370 """
371 self._inference_state.reset_recursion_limitations()
372 definitions = self.goto(line, column, follow_imports=True)
373 if definitions:
374 return definitions
375 leaf = self._module_node.get_leaf_for_position((line, column))
377 if leaf is not None and leaf.end_pos == (line, column) and leaf.type == 'newline':
378 next_ = leaf.get_next_leaf()
379 if next_ is not None and next_.start_pos == leaf.end_pos:
380 leaf = next_
382 if leaf is not None and leaf.type in ('keyword', 'operator', 'error_leaf'):
383 def need_pydoc():
384 if leaf.value in ('(', ')', '[', ']'):
385 if leaf.parent.type == 'trailer':
386 return False
387 if leaf.parent.type == 'atom':
388 return False
389 grammar = self._inference_state.grammar
390 # This parso stuff is not public, but since I control it, this
391 # is fine :-) ~dave
392 reserved = grammar._pgen_grammar.reserved_syntax_strings.keys()
393 return leaf.value in reserved
395 if need_pydoc():
396 name = KeywordName(self._inference_state, leaf.value)
397 return [classes.Name(self._inference_state, name)]
398 return []
400 @validate_line_column
401 def get_references(self, line=None, column=None, **kwargs):
402 """
403 Lists all references of a variable in a project. Since this can be
404 quite hard to do for Jedi, if it is too complicated, Jedi will stop
405 searching.
407 :param include_builtins: Default ``True``. If ``False``, checks if a definition
408 is a builtin (e.g. ``sys``) and in that case does not return it.
409 :param scope: Default ``'project'``. If ``'file'``, include references in
410 the current module only.
411 :rtype: list of :class:`.Name`
412 """
413 self._inference_state.reset_recursion_limitations()
415 def _references(include_builtins=True, scope='project'):
416 if scope not in ('project', 'file'):
417 raise ValueError('Only the scopes "file" and "project" are allowed')
418 tree_name = self._module_node.get_name_of_position((line, column))
419 if tree_name is None:
420 # Must be syntax
421 return []
423 names = find_references(self._get_module_context(), tree_name, scope == 'file')
425 definitions = [classes.Name(self._inference_state, n) for n in names]
426 if not include_builtins or scope == 'file':
427 definitions = [d for d in definitions if not d.in_builtin_module()]
428 return helpers.sorted_definitions(definitions)
429 return _references(**kwargs)
431 @validate_line_column
432 def get_signatures(self, line=None, column=None):
433 """
434 Return the function object of the call under the cursor.
436 E.g. if the cursor is here::
438 abs(# <-- cursor is here
440 This would return the ``abs`` function. On the other hand::
442 abs()# <-- cursor is here
444 This would return an empty list..
446 :rtype: list of :class:`.Signature`
447 """
448 self._inference_state.reset_recursion_limitations()
449 pos = line, column
450 call_details = helpers.get_signature_details(self._module_node, pos)
451 if call_details is None:
452 return []
454 context = self._get_module_context().create_context(call_details.bracket_leaf)
455 definitions = helpers.cache_signatures(
456 self._inference_state,
457 context,
458 call_details.bracket_leaf,
459 self._code_lines,
460 pos
461 )
462 debug.speed('func_call followed')
464 # TODO here we use stubs instead of the actual values. We should use
465 # the signatures from stubs, but the actual values, probably?!
466 return [classes.Signature(self._inference_state, signature, call_details)
467 for signature in definitions.get_signatures()]
469 @validate_line_column
470 def get_context(self, line=None, column=None):
471 """
472 Returns the scope context under the cursor. This basically means the
473 function, class or module where the cursor is at.
475 :rtype: :class:`.Name`
476 """
477 pos = (line, column)
478 leaf = self._module_node.get_leaf_for_position(pos, include_prefixes=True)
479 if leaf.start_pos > pos or leaf.type == 'endmarker':
480 previous_leaf = leaf.get_previous_leaf()
481 if previous_leaf is not None:
482 leaf = previous_leaf
484 module_context = self._get_module_context()
486 n = tree.search_ancestor(leaf, 'funcdef', 'classdef')
487 if n is not None and n.start_pos < pos <= n.children[-1].start_pos:
488 # This is a bit of a special case. The context of a function/class
489 # name/param/keyword is always it's parent context, not the
490 # function itself. Catch all the cases here where we are before the
491 # suite object, but still in the function.
492 context = module_context.create_value(n).as_context()
493 else:
494 context = module_context.create_context(leaf)
496 while context.name is None:
497 context = context.parent_context # comprehensions
499 definition = classes.Name(self._inference_state, context.name)
500 while definition.type != 'module':
501 name = definition._name # TODO private access
502 tree_name = name.tree_name
503 if tree_name is not None: # Happens with lambdas.
504 scope = tree_name.get_definition()
505 if scope.start_pos[1] < column:
506 break
507 definition = definition.parent()
508 return definition
510 def _analysis(self):
511 self._inference_state.is_analysis = True
512 self._inference_state.analysis_modules = [self._module_node]
513 module = self._get_module_context()
514 try:
515 for node in get_executable_nodes(self._module_node):
516 context = module.create_context(node)
517 if node.type in ('funcdef', 'classdef'):
518 # Resolve the decorators.
519 tree_name_to_values(self._inference_state, context, node.children[1])
520 elif isinstance(node, tree.Import):
521 import_names = set(node.get_defined_names())
522 if node.is_nested():
523 import_names |= set(path[-1] for path in node.get_paths())
524 for n in import_names:
525 imports.infer_import(context, n)
526 elif node.type == 'expr_stmt':
527 types = context.infer_node(node)
528 for testlist in node.children[:-1:2]:
529 # Iterate tuples.
530 unpack_tuple_to_dict(context, types, testlist)
531 else:
532 if node.type == 'name':
533 defs = self._inference_state.infer(context, node)
534 else:
535 defs = infer_call_of_leaf(context, node)
536 try_iter_content(defs)
537 self._inference_state.reset_recursion_limitations()
539 ana = [a for a in self._inference_state.analysis if self.path == a.path]
540 return sorted(set(ana), key=lambda x: x.line)
541 finally:
542 self._inference_state.is_analysis = False
544 def get_names(self, **kwargs):
545 """
546 Returns names defined in the current file.
548 :param all_scopes: If True lists the names of all scopes instead of
549 only the module namespace.
550 :param definitions: If True lists the names that have been defined by a
551 class, function or a statement (``a = b`` returns ``a``).
552 :param references: If True lists all the names that are not listed by
553 ``definitions=True``. E.g. ``a = b`` returns ``b``.
554 :rtype: list of :class:`.Name`
555 """
556 names = self._names(**kwargs)
557 return [classes.Name(self._inference_state, n) for n in names]
559 def get_syntax_errors(self):
560 """
561 Lists all syntax errors in the current file.
563 :rtype: list of :class:`.SyntaxError`
564 """
565 return parso_to_jedi_errors(self._inference_state.grammar, self._module_node)
567 def _names(self, all_scopes=False, definitions=True, references=False):
568 self._inference_state.reset_recursion_limitations()
569 # Set line/column to a random position, because they don't matter.
570 module_context = self._get_module_context()
571 defs = [
572 module_context.create_name(name)
573 for name in helpers.get_module_names(
574 self._module_node,
575 all_scopes=all_scopes,
576 definitions=definitions,
577 references=references,
578 )
579 ]
580 return sorted(defs, key=lambda x: x.start_pos)
582 def rename(self, line=None, column=None, *, new_name):
583 """
584 Renames all references of the variable under the cursor.
586 :param new_name: The variable under the cursor will be renamed to this
587 string.
588 :raises: :exc:`.RefactoringError`
589 :rtype: :class:`.Refactoring`
590 """
591 definitions = self.get_references(line, column, include_builtins=False)
592 return refactoring.rename(self._inference_state, definitions, new_name)
594 @validate_line_column
595 def extract_variable(self, line, column, *, new_name, until_line=None, until_column=None):
596 """
597 Moves an expression to a new statement.
599 For example if you have the cursor on ``foo`` and provide a
600 ``new_name`` called ``bar``::
602 foo = 3.1
603 x = int(foo + 1)
605 the code above will become::
607 foo = 3.1
608 bar = foo + 1
609 x = int(bar)
611 :param new_name: The expression under the cursor will be renamed to
612 this string.
613 :param int until_line: The the selection range ends at this line, when
614 omitted, Jedi will be clever and try to define the range itself.
615 :param int until_column: The the selection range ends at this column, when
616 omitted, Jedi will be clever and try to define the range itself.
617 :raises: :exc:`.RefactoringError`
618 :rtype: :class:`.Refactoring`
619 """
620 if until_line is None and until_column is None:
621 until_pos = None
622 else:
623 if until_line is None:
624 until_line = line
625 if until_column is None:
626 until_column = len(self._code_lines[until_line - 1])
627 until_pos = until_line, until_column
628 return extract_variable(
629 self._inference_state, self.path, self._module_node,
630 new_name, (line, column), until_pos
631 )
633 @validate_line_column
634 def extract_function(self, line, column, *, new_name, until_line=None, until_column=None):
635 """
636 Moves an expression to a new function.
638 For example if you have the cursor on ``foo`` and provide a
639 ``new_name`` called ``bar``::
641 global_var = 3
643 def x():
644 foo = 3.1
645 x = int(foo + 1 + global_var)
647 the code above will become::
649 global_var = 3
651 def bar(foo):
652 return int(foo + 1 + global_var)
654 def x():
655 foo = 3.1
656 x = bar(foo)
658 :param new_name: The expression under the cursor will be replaced with
659 a function with this name.
660 :param int until_line: The the selection range ends at this line, when
661 omitted, Jedi will be clever and try to define the range itself.
662 :param int until_column: The the selection range ends at this column, when
663 omitted, Jedi will be clever and try to define the range itself.
664 :raises: :exc:`.RefactoringError`
665 :rtype: :class:`.Refactoring`
666 """
667 if until_line is None and until_column is None:
668 until_pos = None
669 else:
670 if until_line is None:
671 until_line = line
672 if until_column is None:
673 until_column = len(self._code_lines[until_line - 1])
674 until_pos = until_line, until_column
675 return extract_function(
676 self._inference_state, self.path, self._get_module_context(),
677 new_name, (line, column), until_pos
678 )
680 def inline(self, line=None, column=None):
681 """
682 Inlines a variable under the cursor. This is basically the opposite of
683 extracting a variable. For example with the cursor on bar::
685 foo = 3.1
686 bar = foo + 1
687 x = int(bar)
689 the code above will become::
691 foo = 3.1
692 x = int(foo + 1)
694 :raises: :exc:`.RefactoringError`
695 :rtype: :class:`.Refactoring`
696 """
697 names = [d._name for d in self.get_references(line, column, include_builtins=True)]
698 return refactoring.inline(self._inference_state, names)
701class Interpreter(Script):
702 """
703 Jedi's API for Python REPLs.
705 Implements all of the methods that are present in :class:`.Script` as well.
707 In addition to completions that normal REPL completion does like
708 ``str.upper``, Jedi also supports code completion based on static code
709 analysis. For example Jedi will complete ``str().upper``.
711 >>> from os.path import join
712 >>> namespace = locals()
713 >>> script = Interpreter('join("").up', [namespace])
714 >>> print(script.complete()[0].name)
715 upper
717 All keyword arguments are same as the arguments for :class:`.Script`.
719 :param str code: Code to parse.
720 :type namespaces: typing.List[dict]
721 :param namespaces: A list of namespace dictionaries such as the one
722 returned by :func:`globals` and :func:`locals`.
723 """
725 def __init__(self, code, namespaces, *, project=None, **kwds):
726 try:
727 namespaces = [dict(n) for n in namespaces]
728 except Exception:
729 raise TypeError("namespaces must be a non-empty list of dicts.")
731 environment = kwds.get('environment', None)
732 if environment is None:
733 environment = InterpreterEnvironment()
734 else:
735 if not isinstance(environment, InterpreterEnvironment):
736 raise TypeError("The environment needs to be an InterpreterEnvironment subclass.")
738 if project is None:
739 project = Project(Path.cwd())
741 super().__init__(code, environment=environment, project=project, **kwds)
743 self.namespaces = namespaces
744 self._inference_state.allow_unsafe_executions = \
745 settings.allow_unsafe_interpreter_executions
746 # Dynamic params search is important when we work on functions that are
747 # called by other pieces of code. However for interpreter completions
748 # this is not important at all, because the current code is always new
749 # and will never be called by something.
750 # Also sometimes this logic goes a bit too far like in
751 # https://github.com/ipython/ipython/issues/13866, where it takes
752 # seconds to do a simple completion.
753 self._inference_state.do_dynamic_params_search = False
755 @cache.memoize_method
756 def _get_module_context(self):
757 if self.path is None:
758 file_io = None
759 else:
760 file_io = KnownContentFileIO(self.path, self._code)
761 tree_module_value = ModuleValue(
762 self._inference_state, self._module_node,
763 file_io=file_io,
764 string_names=('__main__',),
765 code_lines=self._code_lines,
766 )
767 return interpreter.MixedModuleContext(
768 tree_module_value,
769 self.namespaces,
770 )
773def preload_module(*modules):
774 """
775 Preloading modules tells Jedi to load a module now, instead of lazy parsing
776 of modules. This can be useful for IDEs, to control which modules to load
777 on startup.
779 :param modules: different module names, list of string.
780 """
781 for m in modules:
782 s = "import %s as x; x." % m
783 Script(s).complete(1, len(s))
786def set_debug_function(func_cb=debug.print_to_stdout, warnings=True,
787 notices=True, speed=True):
788 """
789 Define a callback debug function to get all the debug messages.
791 If you don't specify any arguments, debug messages will be printed to stdout.
793 :param func_cb: The callback function for debug messages.
794 """
795 debug.debug_function = func_cb
796 debug.enable_warning = warnings
797 debug.enable_notice = notices
798 debug.enable_speed = speed