Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/jedi-0.18.2-py3.8.egg/jedi/api/__init__.py: 29%
302 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:56 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:56 +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 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()
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.
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.
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_
245 context = self._get_module_context().create_context(leaf)
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 )
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))
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.
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)
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
296 if not names:
297 names = list(name.goto())
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 )
307 defs = [classes.Name(self._inference_state, d) for d in set(names)]
308 # Avoid duplicates
309 return list(set(helpers.sorted_definitions(defs)))
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`.
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)
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 )
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.
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)
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.
359 Typically you will want to display :meth:`.BaseName.docstring` to the
360 user for all the returned definitions.
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.
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))
373 if leaf is not None and leaf.end_pos == (line, column) and leaf.type == 'newline':
374 next_ = leaf.get_next_leaf()
375 if next_ is not None and next_.start_pos == leaf.end_pos:
376 leaf = next_
378 if leaf is not None and leaf.type in ('keyword', 'operator', 'error_leaf'):
379 def need_pydoc():
380 if leaf.value in ('(', ')', '[', ']'):
381 if leaf.parent.type == 'trailer':
382 return False
383 if leaf.parent.type == 'atom':
384 return False
385 grammar = self._inference_state.grammar
386 # This parso stuff is not public, but since I control it, this
387 # is fine :-) ~dave
388 reserved = grammar._pgen_grammar.reserved_syntax_strings.keys()
389 return leaf.value in reserved
391 if need_pydoc():
392 name = KeywordName(self._inference_state, leaf.value)
393 return [classes.Name(self._inference_state, name)]
394 return []
396 @validate_line_column
397 def get_references(self, line=None, column=None, **kwargs):
398 """
399 Lists all references of a variable in a project. Since this can be
400 quite hard to do for Jedi, if it is too complicated, Jedi will stop
401 searching.
403 :param include_builtins: Default ``True``. If ``False``, checks if a definition
404 is a builtin (e.g. ``sys``) and in that case does not return it.
405 :param scope: Default ``'project'``. If ``'file'``, include references in
406 the current module only.
407 :rtype: list of :class:`.Name`
408 """
410 def _references(include_builtins=True, scope='project'):
411 if scope not in ('project', 'file'):
412 raise ValueError('Only the scopes "file" and "project" are allowed')
413 tree_name = self._module_node.get_name_of_position((line, column))
414 if tree_name is None:
415 # Must be syntax
416 return []
418 names = find_references(self._get_module_context(), tree_name, scope == 'file')
420 definitions = [classes.Name(self._inference_state, n) for n in names]
421 if not include_builtins or scope == 'file':
422 definitions = [d for d in definitions if not d.in_builtin_module()]
423 return helpers.sorted_definitions(definitions)
424 return _references(**kwargs)
426 @validate_line_column
427 def get_signatures(self, line=None, column=None):
428 """
429 Return the function object of the call under the cursor.
431 E.g. if the cursor is here::
433 abs(# <-- cursor is here
435 This would return the ``abs`` function. On the other hand::
437 abs()# <-- cursor is here
439 This would return an empty list..
441 :rtype: list of :class:`.Signature`
442 """
443 pos = line, column
444 call_details = helpers.get_signature_details(self._module_node, pos)
445 if call_details is None:
446 return []
448 context = self._get_module_context().create_context(call_details.bracket_leaf)
449 definitions = helpers.cache_signatures(
450 self._inference_state,
451 context,
452 call_details.bracket_leaf,
453 self._code_lines,
454 pos
455 )
456 debug.speed('func_call followed')
458 # TODO here we use stubs instead of the actual values. We should use
459 # the signatures from stubs, but the actual values, probably?!
460 return [classes.Signature(self._inference_state, signature, call_details)
461 for signature in definitions.get_signatures()]
463 @validate_line_column
464 def get_context(self, line=None, column=None):
465 """
466 Returns the scope context under the cursor. This basically means the
467 function, class or module where the cursor is at.
469 :rtype: :class:`.Name`
470 """
471 pos = (line, column)
472 leaf = self._module_node.get_leaf_for_position(pos, include_prefixes=True)
473 if leaf.start_pos > pos or leaf.type == 'endmarker':
474 previous_leaf = leaf.get_previous_leaf()
475 if previous_leaf is not None:
476 leaf = previous_leaf
478 module_context = self._get_module_context()
480 n = tree.search_ancestor(leaf, 'funcdef', 'classdef')
481 if n is not None and n.start_pos < pos <= n.children[-1].start_pos:
482 # This is a bit of a special case. The context of a function/class
483 # name/param/keyword is always it's parent context, not the
484 # function itself. Catch all the cases here where we are before the
485 # suite object, but still in the function.
486 context = module_context.create_value(n).as_context()
487 else:
488 context = module_context.create_context(leaf)
490 while context.name is None:
491 context = context.parent_context # comprehensions
493 definition = classes.Name(self._inference_state, context.name)
494 while definition.type != 'module':
495 name = definition._name # TODO private access
496 tree_name = name.tree_name
497 if tree_name is not None: # Happens with lambdas.
498 scope = tree_name.get_definition()
499 if scope.start_pos[1] < column:
500 break
501 definition = definition.parent()
502 return definition
504 def _analysis(self):
505 self._inference_state.is_analysis = True
506 self._inference_state.analysis_modules = [self._module_node]
507 module = self._get_module_context()
508 try:
509 for node in get_executable_nodes(self._module_node):
510 context = module.create_context(node)
511 if node.type in ('funcdef', 'classdef'):
512 # Resolve the decorators.
513 tree_name_to_values(self._inference_state, context, node.children[1])
514 elif isinstance(node, tree.Import):
515 import_names = set(node.get_defined_names())
516 if node.is_nested():
517 import_names |= set(path[-1] for path in node.get_paths())
518 for n in import_names:
519 imports.infer_import(context, n)
520 elif node.type == 'expr_stmt':
521 types = context.infer_node(node)
522 for testlist in node.children[:-1:2]:
523 # Iterate tuples.
524 unpack_tuple_to_dict(context, types, testlist)
525 else:
526 if node.type == 'name':
527 defs = self._inference_state.infer(context, node)
528 else:
529 defs = infer_call_of_leaf(context, node)
530 try_iter_content(defs)
531 self._inference_state.reset_recursion_limitations()
533 ana = [a for a in self._inference_state.analysis if self.path == a.path]
534 return sorted(set(ana), key=lambda x: x.line)
535 finally:
536 self._inference_state.is_analysis = False
538 def get_names(self, **kwargs):
539 """
540 Returns names defined in the current file.
542 :param all_scopes: If True lists the names of all scopes instead of
543 only the module namespace.
544 :param definitions: If True lists the names that have been defined by a
545 class, function or a statement (``a = b`` returns ``a``).
546 :param references: If True lists all the names that are not listed by
547 ``definitions=True``. E.g. ``a = b`` returns ``b``.
548 :rtype: list of :class:`.Name`
549 """
550 names = self._names(**kwargs)
551 return [classes.Name(self._inference_state, n) for n in names]
553 def get_syntax_errors(self):
554 """
555 Lists all syntax errors in the current file.
557 :rtype: list of :class:`.SyntaxError`
558 """
559 return parso_to_jedi_errors(self._inference_state.grammar, self._module_node)
561 def _names(self, all_scopes=False, definitions=True, references=False):
562 # Set line/column to a random position, because they don't matter.
563 module_context = self._get_module_context()
564 defs = [
565 module_context.create_name(name)
566 for name in helpers.get_module_names(
567 self._module_node,
568 all_scopes=all_scopes,
569 definitions=definitions,
570 references=references,
571 )
572 ]
573 return sorted(defs, key=lambda x: x.start_pos)
575 def rename(self, line=None, column=None, *, new_name):
576 """
577 Renames all references of the variable under the cursor.
579 :param new_name: The variable under the cursor will be renamed to this
580 string.
581 :raises: :exc:`.RefactoringError`
582 :rtype: :class:`.Refactoring`
583 """
584 definitions = self.get_references(line, column, include_builtins=False)
585 return refactoring.rename(self._inference_state, definitions, new_name)
587 @validate_line_column
588 def extract_variable(self, line, column, *, new_name, until_line=None, until_column=None):
589 """
590 Moves an expression to a new statement.
592 For example if you have the cursor on ``foo`` and provide a
593 ``new_name`` called ``bar``::
595 foo = 3.1
596 x = int(foo + 1)
598 the code above will become::
600 foo = 3.1
601 bar = foo + 1
602 x = int(bar)
604 :param new_name: The expression under the cursor will be renamed to
605 this string.
606 :param int until_line: The the selection range ends at this line, when
607 omitted, Jedi will be clever and try to define the range itself.
608 :param int until_column: The the selection range ends at this column, when
609 omitted, Jedi will be clever and try to define the range itself.
610 :raises: :exc:`.RefactoringError`
611 :rtype: :class:`.Refactoring`
612 """
613 if until_line is None and until_column is None:
614 until_pos = None
615 else:
616 if until_line is None:
617 until_line = line
618 if until_column is None:
619 until_column = len(self._code_lines[until_line - 1])
620 until_pos = until_line, until_column
621 return extract_variable(
622 self._inference_state, self.path, self._module_node,
623 new_name, (line, column), until_pos
624 )
626 @validate_line_column
627 def extract_function(self, line, column, *, new_name, until_line=None, until_column=None):
628 """
629 Moves an expression to a new function.
631 For example if you have the cursor on ``foo`` and provide a
632 ``new_name`` called ``bar``::
634 global_var = 3
636 def x():
637 foo = 3.1
638 x = int(foo + 1 + global_var)
640 the code above will become::
642 global_var = 3
644 def bar(foo):
645 return int(foo + 1 + global_var)
647 def x():
648 foo = 3.1
649 x = bar(foo)
651 :param new_name: The expression under the cursor will be replaced with
652 a function with this name.
653 :param int until_line: The the selection range ends at this line, when
654 omitted, Jedi will be clever and try to define the range itself.
655 :param int until_column: The the selection range ends at this column, when
656 omitted, Jedi will be clever and try to define the range itself.
657 :raises: :exc:`.RefactoringError`
658 :rtype: :class:`.Refactoring`
659 """
660 if until_line is None and until_column is None:
661 until_pos = None
662 else:
663 if until_line is None:
664 until_line = line
665 if until_column is None:
666 until_column = len(self._code_lines[until_line - 1])
667 until_pos = until_line, until_column
668 return extract_function(
669 self._inference_state, self.path, self._get_module_context(),
670 new_name, (line, column), until_pos
671 )
673 def inline(self, line=None, column=None):
674 """
675 Inlines a variable under the cursor. This is basically the opposite of
676 extracting a variable. For example with the cursor on bar::
678 foo = 3.1
679 bar = foo + 1
680 x = int(bar)
682 the code above will become::
684 foo = 3.1
685 x = int(foo + 1)
687 :raises: :exc:`.RefactoringError`
688 :rtype: :class:`.Refactoring`
689 """
690 names = [d._name for d in self.get_references(line, column, include_builtins=True)]
691 return refactoring.inline(self._inference_state, names)
694class Interpreter(Script):
695 """
696 Jedi's API for Python REPLs.
698 Implements all of the methods that are present in :class:`.Script` as well.
700 In addition to completions that normal REPL completion does like
701 ``str.upper``, Jedi also supports code completion based on static code
702 analysis. For example Jedi will complete ``str().upper``.
704 >>> from os.path import join
705 >>> namespace = locals()
706 >>> script = Interpreter('join("").up', [namespace])
707 >>> print(script.complete()[0].name)
708 upper
710 All keyword arguments are same as the arguments for :class:`.Script`.
712 :param str code: Code to parse.
713 :type namespaces: typing.List[dict]
714 :param namespaces: A list of namespace dictionaries such as the one
715 returned by :func:`globals` and :func:`locals`.
716 """
718 def __init__(self, code, namespaces, *, project=None, **kwds):
719 try:
720 namespaces = [dict(n) for n in namespaces]
721 except Exception:
722 raise TypeError("namespaces must be a non-empty list of dicts.")
724 environment = kwds.get('environment', None)
725 if environment is None:
726 environment = InterpreterEnvironment()
727 else:
728 if not isinstance(environment, InterpreterEnvironment):
729 raise TypeError("The environment needs to be an InterpreterEnvironment subclass.")
731 if project is None:
732 project = Project(Path.cwd())
734 super().__init__(code, environment=environment, project=project, **kwds)
736 self.namespaces = namespaces
737 self._inference_state.allow_descriptor_getattr = settings.instance_allow_descriptor_getattr
739 @cache.memoize_method
740 def _get_module_context(self):
741 if self.path is None:
742 file_io = None
743 else:
744 file_io = KnownContentFileIO(self.path, self._code)
745 tree_module_value = ModuleValue(
746 self._inference_state, self._module_node,
747 file_io=file_io,
748 string_names=('__main__',),
749 code_lines=self._code_lines,
750 )
751 return interpreter.MixedModuleContext(
752 tree_module_value,
753 self.namespaces,
754 )
757def preload_module(*modules):
758 """
759 Preloading modules tells Jedi to load a module now, instead of lazy parsing
760 of modules. This can be useful for IDEs, to control which modules to load
761 on startup.
763 :param modules: different module names, list of string.
764 """
765 for m in modules:
766 s = "import %s as x; x." % m
767 Script(s).complete(1, len(s))
770def set_debug_function(func_cb=debug.print_to_stdout, warnings=True,
771 notices=True, speed=True):
772 """
773 Define a callback debug function to get all the debug messages.
775 If you don't specify any arguments, debug messages will be printed to stdout.
777 :param func_cb: The callback function for debug messages.
778 """
779 debug.debug_function = func_cb
780 debug.enable_warning = warnings
781 debug.enable_notice = notices
782 debug.enable_speed = speed