2 There are a couple of classes documented in here:
4 - :class:`.BaseName` as an abstact base class for almost everything.
5 - :class:`.Name` used in a lot of places
6 - :class:`.Completion` for completions
7 - :class:`.BaseSignature` as a base class for signatures
8 - :class:`.Signature` for :meth:`.Script.get_signatures` only
9 - :class:`.ParamName` used for parameters of signatures
10 - :class:`.Refactoring` for refactorings
11 - :class:`.SyntaxError` for :meth:`.Script.get_syntax_errors` only
13 These classes are the much biggest part of the API, because they contain
14 the interesting information about all operations.
17 from pathlib
import Path
18 from typing
import Optional
20 from parso
.tree
import search_ancestor
22 from jedi
import settings
23 from jedi
import debug
24 from jedi
.inference
.utils
import unite
25 from jedi
.cache
import memoize_method
26 from jedi
.inference
.compiled
.mixed
import MixedName
27 from jedi
.inference
.names
import ImportName
, SubModuleName
28 from jedi
.inference
.gradual
.stub_value
import StubModuleValue
29 from jedi
.inference
.gradual
.conversion
import convert_names
, convert_values
30 from jedi
.inference
.base_value
import ValueSet
, HasNoContext
31 from jedi
.api
.keywords
import KeywordName
32 from jedi
.api
import completion_cache
33 from jedi
.api
.helpers
import filter_follow_imports
36 def _sort_names_by_start_pos(names
):
37 return sorted(names
, key
=lambda s
: s
.start_pos
or (0, 0))
40 def defined_names(inference_state
, value
):
42 List sub-definitions (e.g., methods in class).
48 context
= value
.as_context()
51 filter = next(context
.get_filters())
52 names
= [name
for name
in filter.values()]
53 return [Name(inference_state
, n
) for n
in _sort_names_by_start_pos(names
)]
56 def _values_to_definitions(values
):
57 return [Name(c
.inference_state
, c
.name
) for c
in values
]
62 The base class for all definitions, completions and signatures.
65 'posixpath': 'os.path',
66 'riscospath': 'os.path',
68 'os2emxpath': 'os.path',
70 'genericpath': 'os.path',
73 '_functools': 'functools',
74 '_collections': 'collections',
76 '_sqlite3': 'sqlite3',
79 _tuple_mapping
= dict((tuple(k
.split('.')), v
) for (k
, v
) in {
80 'argparse._ActionsContainer': 'argparse.ArgumentParser',
83 def __init__(self
, inference_state
, name
):
84 self
._inference
_state
= inference_state
87 An instance of :class:`parso.python.tree.Name` subclass.
89 self
.is_keyword
= isinstance(self
._name
, KeywordName
)
92 def _get_module_context(self
):
93 # This can take a while to complete, because in the worst case of
94 # imports (consider `import a` completions), we need to load all
95 # modules starting with a first.
96 return self
._name
.get_root_context()
99 def module_path(self
) -> Optional
[Path
]:
101 Shows the file path of a module. e.g. ``/usr/lib/python3.9/os.py``
103 module
= self
._get
_module
_context
()
104 if module
.is_stub() or not module
.is_compiled():
105 # Compiled modules should not return a module path even if they
107 path
: Optional
[Path
] = self
._get
_module
_context
().py__file__()
115 Name of variable/function/class/module.
117 For example, for ``x = None`` it returns ``'x'``.
121 return self
._name
.get_public_name()
126 The type of the definition.
128 Here is an example of the value of this attribute. Let's consider
129 the following source. As what is in ``variable`` is unambiguous
130 to Jedi, :meth:`jedi.Script.infer` should return a list of
131 definition for ``sys``, ``f``, ``C`` and ``x``.
133 >>> from jedi import Script
148 ... for variable in [keyword, f, C, x]:
151 >>> script = Script(source)
152 >>> defs = script.infer()
154 Before showing what is in ``defs``, let's sort it by :attr:`line`
155 so that it is easy to relate the result to the source code.
157 >>> defs = sorted(defs, key=lambda d: d.line)
158 >>> print(defs) # doctest: +NORMALIZE_WHITESPACE
159 [<Name full_name='keyword', description='module keyword'>,
160 <Name full_name='__main__.C', description='class C'>,
161 <Name full_name='__main__.D', description='instance D'>,
162 <Name full_name='__main__.f', description='def f'>]
164 Finally, here is what you can get from :attr:`type`:
166 >>> defs = [d.type for d in defs]
176 Valid values for type are ``module``, ``class``, ``instance``, ``function``,
177 ``param``, ``path``, ``keyword``, ``property`` and ``statement``.
180 tree_name
= self
._name
.tree_name
182 if tree_name
is not None:
183 # TODO move this to their respective names.
184 definition
= tree_name
.get_definition()
185 if definition
is not None and definition
.type == 'import_from' and \
186 tree_name
.is_definition():
189 if isinstance(self
._name
, SubModuleName
) or resolve
:
190 for value
in self
._name
.infer():
191 return value
.api_type
192 return self
._name
.api_type
195 def module_name(self
):
197 The module name, a bit similar to what ``__name__`` is in a random
200 >>> from jedi import Script
201 >>> source = 'import json'
202 >>> script = Script(source, path='example.py')
203 >>> d = script.infer()[0]
204 >>> print(d.module_name) # doctest: +ELLIPSIS
207 return self
._get
_module
_context
().py__name__()
209 def in_builtin_module(self
):
211 Returns True, if this is a builtin module.
213 value
= self
._get
_module
_context
().get_value()
214 if isinstance(value
, StubModuleValue
):
215 return any(v
.is_compiled() for v
in value
.non_stub_value_set
)
216 return value
.is_compiled()
220 """The line where the definition occurs (starting with 1)."""
221 start_pos
= self
._name
.start_pos
222 if start_pos
is None:
228 """The column where the definition occurs (starting with 0)."""
229 start_pos
= self
._name
.start_pos
230 if start_pos
is None:
234 def get_definition_start_position(self
):
236 The (row, column) of the start of the definition range. Rows start with
237 1, columns start with 0.
239 :rtype: Optional[Tuple[int, int]]
241 if self
._name
.tree_name
is None:
243 definition
= self
._name
.tree_name
.get_definition()
244 if definition
is None:
245 return self
._name
.start_pos
246 return definition
.start_pos
248 def get_definition_end_position(self
):
250 The (row, column) of the end of the definition range. Rows start with
251 1, columns start with 0.
253 :rtype: Optional[Tuple[int, int]]
255 if self
._name
.tree_name
is None:
257 definition
= self
._name
.tree_name
.get_definition()
258 if definition
is None:
259 return self
._name
.tree_name
.end_pos
260 if self
.type in ("function", "class"):
261 last_leaf
= definition
.get_last_leaf()
262 if last_leaf
.type == "newline":
263 return last_leaf
.get_previous_leaf().end_pos
264 return last_leaf
.end_pos
265 return definition
.end_pos
267 def docstring(self
, raw
=False, fast
=True):
269 Return a document string for this completion object.
273 >>> from jedi import Script
276 ... "Document for function f."
278 >>> script = Script(source, path='example.py')
279 >>> doc = script.infer(1, len('def f'))[0].docstring()
283 Document for function f.
285 Notice that useful extra information is added to the actual
286 docstring, e.g. function signatures are prepended to their docstrings.
287 If you need the actual docstring, use ``raw=True`` instead.
289 >>> print(script.infer(1, len('def f'))[0].docstring(raw=True))
290 Document for function f.
292 :param fast: Don't follow imports that are only one level deep like
293 ``import foo``, but follow ``from foo import bar``. This makes
294 sense for speed reasons. Completing `import a` is slow if you use
295 the ``foo.docstring(fast=False)`` on every object, because it
296 parses all libraries starting with ``a``.
298 if isinstance(self
._name
, ImportName
) and fast
:
300 doc
= self
._get
_docstring
()
304 signature_text
= self
._get
_docstring
_signature
()
305 if signature_text
and doc
:
306 return signature_text
+ '\n\n' + doc
308 return signature_text
+ doc
310 def _get_docstring(self
):
311 return self
._name
.py__doc__()
313 def _get_docstring_signature(self
):
315 signature
.to_string()
316 for signature
in self
._get
_signatures
(for_docstring
=True)
320 def description(self
):
322 A description of the :class:`.Name` object, which is heavily used
323 in testing. e.g. for ``isinstance`` it returns ``def isinstance``.
327 >>> from jedi import Script
335 ... variable = f if random.choice([0,1]) else C'''
336 >>> script = Script(source) # line is maximum by default
337 >>> defs = script.infer(column=3)
338 >>> defs = sorted(defs, key=lambda d: d.line)
339 >>> print(defs) # doctest: +NORMALIZE_WHITESPACE
340 [<Name full_name='__main__.f', description='def f'>,
341 <Name full_name='__main__.C', description='class C'>]
342 >>> str(defs[0].description)
344 >>> str(defs[1].description)
349 tree_name
= self
._name
.tree_name
351 return typ
+ ' ' + self
._name
.to_string()
352 if typ
in ('function', 'class', 'module', 'instance') or tree_name
is None:
353 if typ
== 'function':
354 # For the description we want a short and a pythonic way.
356 return typ
+ ' ' + self
._name
.get_public_name()
358 definition
= tree_name
.get_definition(include_setitem
=True) or tree_name
359 # Remove the prefix, because that's not what we want for get_code
361 txt
= definition
.get_code(include_prefix
=False)
363 txt
= re
.sub(r
'#[^\n]+\n', ' ', txt
)
364 # Delete multi spaces/newlines
365 txt
= re
.sub(r
'\s+', ' ', txt
).strip()
371 Dot-separated path of this object.
373 It is in the form of ``<module>[.<submodule>[...]][.<object>]``.
374 It is useful when you want to look up Python manual of the
379 >>> from jedi import Script
383 >>> script = Script(source, path='example.py')
384 >>> print(script.infer(3, len('os.path.join'))[0].full_name)
387 Notice that it returns ``'os.path.join'`` instead of (for example)
388 ``'posixpath.join'``. This is not correct, since the modules name would
389 be ``<module 'posixpath' ...>```. However most users find the latter
392 if not self
._name
.is_value_name
:
395 names
= self
._name
.get_qualified_names(include_module_names
=True)
401 names
[0] = self
._mapping
[names
[0]]
405 return '.'.join(names
)
409 Returns True if the current name is defined in a stub file.
411 if not self
._name
.is_value_name
:
414 return self
._name
.get_root_context().is_stub()
416 def is_side_effect(self
):
418 Checks if a name is defined as ``self.foo = 3``. In case of self, this
419 function would return False, for foo it would return True.
421 tree_name
= self
._name
.tree_name
422 if tree_name
is None:
424 return tree_name
.is_definition() and tree_name
.parent
.type == 'trailer'
426 @debug.increase_indent_cm('goto on name')
427 def goto(self
, *, follow_imports
=False, follow_builtin_imports
=False,
428 only_stubs
=False, prefer_stubs
=False):
431 Like :meth:`.Script.goto` (also supports the same params), but does it
432 for the current name. This is typically useful if you are using
433 something like :meth:`.Script.get_names()`.
435 :param follow_imports: The goto call will follow imports.
436 :param follow_builtin_imports: If follow_imports is True will try to
437 look up names in builtins (i.e. compiled or extension modules).
438 :param only_stubs: Only return stubs for this goto call.
439 :param prefer_stubs: Prefer stubs to Python objects for this goto call.
440 :rtype: list of :class:`Name`
442 if not self
._name
.is_value_name
:
445 names
= self
._name
.goto()
447 names
= filter_follow_imports(names
, follow_builtin_imports
)
448 names
= convert_names(
450 only_stubs
=only_stubs
,
451 prefer_stubs
=prefer_stubs
,
453 return [self
if n
== self
._name
else Name(self
._inference
_state
, n
)
456 @debug.increase_indent_cm('infer on name')
457 def infer(self
, *, only_stubs
=False, prefer_stubs
=False):
459 Like :meth:`.Script.infer`, it can be useful to understand which type
460 the current name has.
462 Return the actual definitions. I strongly recommend not using it for
463 your completions, because it might slow down |jedi|. If you want to
464 read only a few objects (<=20), it might be useful, especially to get
465 the original docstrings. The basic problem of this function is that it
466 follows all results. This means with 1000 completions (e.g. numpy),
467 it's just very, very slow.
469 :param only_stubs: Only return stubs for this goto call.
470 :param prefer_stubs: Prefer stubs to Python objects for this type
472 :rtype: list of :class:`Name`
474 assert not (only_stubs
and prefer_stubs
)
476 if not self
._name
.is_value_name
:
479 # First we need to make sure that we have stub names (if possible) that
480 # we can follow. If we don't do that, we can end up with the inferred
481 # results of Python objects instead of stubs.
482 names
= convert_names([self
._name
], prefer_stubs
=True)
483 values
= convert_values(
484 ValueSet
.from_sets(n
.infer() for n
in names
),
485 only_stubs
=only_stubs
,
486 prefer_stubs
=prefer_stubs
,
488 resulting_names
= [c
.name
for c
in values
]
489 return [self
if n
== self
._name
else Name(self
._inference
_state
, n
)
490 for n
in resulting_names
]
494 Returns the parent scope of this identifier.
498 if not self
._name
.is_value_name
:
501 if self
.type in ('function', 'class', 'param') and self
._name
.tree_name
is not None:
502 # Since the parent_context doesn't really match what the user
503 # thinks of that the parent is here, we do these cases separately.
504 # The reason for this is the following:
505 # - class: Nested classes parent_context is always the
506 # parent_context of the most outer one.
507 # - function: Functions in classes have the module as
509 # - param: The parent_context of a param is not its function but
510 # e.g. the outer class or module.
511 cls_or_func_node
= self
._name
.tree_name
.get_definition()
512 parent
= search_ancestor(cls_or_func_node
, 'funcdef', 'classdef', 'file_input')
513 context
= self
._get
_module
_context
().create_value(parent
).as_context()
515 context
= self
._name
.parent_context
519 while context
.name
is None:
520 # Happens for comprehension contexts
521 context
= context
.parent_context
523 return Name(self
._inference
_state
, context
.name
)
526 return "<%s %sname=%r, description=%r>" % (
527 self
.__class
__.__name
__,
528 'full_' if self
.full_name
else '',
529 self
.full_name
or self
.name
,
533 def get_line_code(self
, before
=0, after
=0):
535 Returns the line of code where this object was defined.
537 :param before: Add n lines before the current line to the output.
538 :param after: Add n lines after the current line to the output.
540 :return str: Returns the line(s) of code or an empty string if it's a
543 if not self
._name
.is_value_name
:
546 lines
= self
._name
.get_root_context().code_lines
548 # Probably a builtin module, just ignore in that case.
551 index
= self
._name
.start_pos
[0] - 1
552 start_index
= max(index
- before
, 0)
553 return ''.join(lines
[start_index
:index
+ after
+ 1])
555 def _get_signatures(self
, for_docstring
=False):
556 if self
._name
.api_type
== 'property':
558 if for_docstring
and self
._name
.api_type
== 'statement' and not self
.is_stub():
559 # For docstrings we don't resolve signatures if they are simple
560 # statements and not stubs. This is a speed optimization.
563 if isinstance(self
._name
, MixedName
):
564 # While this would eventually happen anyway, it's basically just a
565 # shortcut to not infer anything tree related, because it's really
567 return self
._name
.infer_compiled_value().get_signatures()
569 names
= convert_names([self
._name
], prefer_stubs
=True)
570 return [sig
for name
in names
for sig
in name
.infer().get_signatures()]
572 def get_signatures(self
):
574 Returns all potential signatures for a function or a class. Multiple
575 signatures are typical if you use Python stubs with ``@overload``.
577 :rtype: list of :class:`BaseSignature`
580 BaseSignature(self
._inference
_state
, s
)
581 for s
in self
._get
_signatures
()
586 Uses type inference to "execute" this identifier and returns the
589 :rtype: list of :class:`Name`
591 return _values_to_definitions(self
._name
.infer().execute_with_values())
593 def get_type_hint(self
):
595 Returns type hints like ``Iterable[int]`` or ``Union[int, str]``.
597 This method might be quite slow, especially for functions. The problem
598 is finding executions for those functions to return something like
599 ``Callable[[int, str], str]``.
603 return self
._name
.infer().get_type_hint()
606 class Completion(BaseName
):
608 ``Completion`` objects are returned from :meth:`.Script.complete`. They
609 provide additional information about a completion.
611 def __init__(self
, inference_state
, name
, stack
, like_name_length
,
612 is_fuzzy
, cached_name
=None):
613 super().__init
__(inference_state
, name
)
615 self
._like
_name
_length
= like_name_length
617 self
._is
_fuzzy
= is_fuzzy
618 self
._cached
_name
= cached_name
620 # Completion objects with the same Completion name (which means
621 # duplicate items in the completion)
622 self
._same
_name
_completions
= []
624 def _complete(self
, like_name
):
626 if settings
.add_bracket_after_function \
627 and self
.type == 'function':
630 name
= self
._name
.get_public_name()
632 name
= name
[self
._like
_name
_length
:]
638 Only works with non-fuzzy completions. Returns None if fuzzy
639 completions are used.
641 Return the rest of the word, e.g. completing ``isinstance``::
643 isinstan# <-- Cursor is here
645 would return the string 'ce'. It also adds additional stuff, depending
646 on your ``settings.py``.
648 Assuming the following function definition::
653 completing ``foo(par`` would give a ``Completion`` which ``complete``
658 return self
._complete
(True)
661 def name_with_symbols(self
):
663 Similar to :attr:`.name`, but like :attr:`.name` returns also the
664 symbols, for example assuming the following function definition::
669 completing ``foo(`` would give a ``Completion`` which
670 ``name_with_symbols`` would be "param=".
673 return self
._complete
(False)
675 def docstring(self
, raw
=False, fast
=True):
677 Documented under :meth:`BaseName.docstring`.
679 if self
._like
_name
_length
>= 3:
680 # In this case we can just resolve the like name, because we
681 # wouldn't load like > 100 Python modules anymore.
684 return super().docstring(raw
=raw
, fast
=fast
)
686 def _get_docstring(self
):
687 if self
._cached
_name
is not None:
688 return completion_cache
.get_docstring(
690 self
._name
.get_public_name(),
691 lambda: self
._get
_cache
()
693 return super()._get
_docstring
()
695 def _get_docstring_signature(self
):
696 if self
._cached
_name
is not None:
697 return completion_cache
.get_docstring_signature(
699 self
._name
.get_public_name(),
700 lambda: self
._get
_cache
()
702 return super()._get
_docstring
_signature
()
704 def _get_cache(self
):
707 super()._get
_docstring
_signature
(),
708 super()._get
_docstring
(),
714 Documented under :meth:`BaseName.type`.
716 # Purely a speed optimization.
717 if self
._cached
_name
is not None:
718 return completion_cache
.get_type(
720 self
._name
.get_public_name(),
721 lambda: self
._get
_cache
()
726 def get_completion_prefix_length(self
):
728 Returns the length of the prefix being completed.
729 For example, completing ``isinstance``::
731 isinstan# <-- Cursor is here
733 would return 8, because len('isinstan') == 8.
735 Assuming the following function definition::
740 completing ``foo(par`` would return 3.
742 return self
._like
_name
_length
745 return '<%s: %s>' % (type(self
).__name
__, self
._name
.get_public_name())
748 class Name(BaseName
):
750 *Name* objects are returned from many different APIs including
751 :meth:`.Script.goto` or :meth:`.Script.infer`.
753 def __init__(self
, inference_state
, definition
):
754 super().__init
__(inference_state
, definition
)
757 def defined_names(self
):
759 List sub-definitions (e.g., methods in class).
761 :rtype: list of :class:`Name`
763 defs
= self
._name
.infer()
765 unite(defined_names(self
._inference
_state
, d
) for d
in defs
),
766 key
=lambda s
: s
._name
.start_pos
or (0, 0)
769 def is_definition(self
):
771 Returns True, if defined as a name in a statement, function or class.
772 Returns False, if it's a reference to such a definition.
774 if self
._name
.tree_name
is None:
777 return self
._name
.tree_name
.is_definition()
779 def __eq__(self
, other
):
780 return self
._name
.start_pos
== other
._name
.start_pos \
781 and self
.module_path
== other
.module_path \
782 and self
.name
== other
.name \
783 and self
._inference
_state
== other
._inference
_state
785 def __ne__(self
, other
):
786 return not self
.__eq
__(other
)
789 return hash((self
._name
.start_pos
, self
.module_path
, self
.name
, self
._inference
_state
))
792 class BaseSignature(Name
):
794 These signatures are returned by :meth:`BaseName.get_signatures`
797 def __init__(self
, inference_state
, signature
):
798 super().__init
__(inference_state
, signature
.name
)
799 self
._signature
= signature
804 Returns definitions for all parameters that a signature defines.
805 This includes stuff like ``*args`` and ``**kwargs``.
807 :rtype: list of :class:`.ParamName`
809 return [ParamName(self
._inference
_state
, n
)
810 for n
in self
._signature
.get_param_names(resolve_stars
=True)]
814 Returns a text representation of the signature. This could for example
815 look like ``foo(bar, baz: int, **kwargs)``.
819 return self
._signature
.to_string()
822 class Signature(BaseSignature
):
824 A full signature object is the return value of
825 :meth:`.Script.get_signatures`.
827 def __init__(self
, inference_state
, signature
, call_details
):
828 super().__init
__(inference_state
, signature
)
829 self
._call
_details
= call_details
830 self
._signature
= signature
835 Returns the param index of the current cursor position.
836 Returns None if the index cannot be found in the curent call.
840 return self
._call
_details
.calculate_index(
841 self
._signature
.get_param_names(resolve_stars
=True)
845 def bracket_start(self
):
847 Returns a line/column tuple of the bracket that is responsible for the
848 last function call. The first line is 1 and the first column 0.
852 return self
._call
_details
.bracket_leaf
.start_pos
855 return '<%s: index=%r %s>' % (
858 self
._signature
.to_string(),
862 class ParamName(Name
):
863 def infer_default(self
):
865 Returns default values like the ``1`` of ``def foo(x=1):``.
867 :rtype: list of :class:`.Name`
869 return _values_to_definitions(self
._name
.infer_default())
871 def infer_annotation(self
, **kwargs
):
873 :param execute_annotation: Default True; If False, values are not
874 executed and classes are returned instead of instances.
875 :rtype: list of :class:`.Name`
877 return _values_to_definitions(self
._name
.infer_annotation(ignore_stars
=True, **kwargs
))
881 Returns a simple representation of a param, like
882 ``f: Callable[..., Any]``.
886 return self
._name
.to_string()
891 Returns an enum instance of :mod:`inspect`'s ``Parameter`` enum.
893 :rtype: :py:attr:`inspect.Parameter.kind`
895 return self
._name
.get_kind()