classes.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. """
  2. There are a couple of classes documented in here:
  3. - :class:`.BaseName` as an abstact base class for almost everything.
  4. - :class:`.Name` used in a lot of places
  5. - :class:`.Completion` for completions
  6. - :class:`.BaseSignature` as a base class for signatures
  7. - :class:`.Signature` for :meth:`.Script.get_signatures` only
  8. - :class:`.ParamName` used for parameters of signatures
  9. - :class:`.Refactoring` for refactorings
  10. - :class:`.SyntaxError` for :meth:`.Script.get_syntax_errors` only
  11. These classes are the much biggest part of the API, because they contain
  12. the interesting information about all operations.
  13. """
  14. import re
  15. from pathlib import Path
  16. from typing import Optional
  17. from parso.tree import search_ancestor
  18. from jedi import settings
  19. from jedi import debug
  20. from jedi.inference.utils import unite
  21. from jedi.cache import memoize_method
  22. from jedi.inference.compiled.mixed import MixedName
  23. from jedi.inference.names import ImportName, SubModuleName
  24. from jedi.inference.gradual.stub_value import StubModuleValue
  25. from jedi.inference.gradual.conversion import convert_names, convert_values
  26. from jedi.inference.base_value import ValueSet, HasNoContext
  27. from jedi.api.keywords import KeywordName
  28. from jedi.api import completion_cache
  29. from jedi.api.helpers import filter_follow_imports
  30. def _sort_names_by_start_pos(names):
  31. return sorted(names, key=lambda s: s.start_pos or (0, 0))
  32. def defined_names(inference_state, value):
  33. """
  34. List sub-definitions (e.g., methods in class).
  35. :type scope: Scope
  36. :rtype: list of Name
  37. """
  38. try:
  39. context = value.as_context()
  40. except HasNoContext:
  41. return []
  42. filter = next(context.get_filters())
  43. names = [name for name in filter.values()]
  44. return [Name(inference_state, n) for n in _sort_names_by_start_pos(names)]
  45. def _values_to_definitions(values):
  46. return [Name(c.inference_state, c.name) for c in values]
  47. class BaseName:
  48. """
  49. The base class for all definitions, completions and signatures.
  50. """
  51. _mapping = {
  52. 'posixpath': 'os.path',
  53. 'riscospath': 'os.path',
  54. 'ntpath': 'os.path',
  55. 'os2emxpath': 'os.path',
  56. 'macpath': 'os.path',
  57. 'genericpath': 'os.path',
  58. 'posix': 'os',
  59. '_io': 'io',
  60. '_functools': 'functools',
  61. '_collections': 'collections',
  62. '_socket': 'socket',
  63. '_sqlite3': 'sqlite3',
  64. }
  65. _tuple_mapping = dict((tuple(k.split('.')), v) for (k, v) in {
  66. 'argparse._ActionsContainer': 'argparse.ArgumentParser',
  67. }.items())
  68. def __init__(self, inference_state, name):
  69. self._inference_state = inference_state
  70. self._name = name
  71. """
  72. An instance of :class:`parso.python.tree.Name` subclass.
  73. """
  74. self.is_keyword = isinstance(self._name, KeywordName)
  75. @memoize_method
  76. def _get_module_context(self):
  77. # This can take a while to complete, because in the worst case of
  78. # imports (consider `import a` completions), we need to load all
  79. # modules starting with a first.
  80. return self._name.get_root_context()
  81. @property
  82. def module_path(self) -> Optional[Path]:
  83. """
  84. Shows the file path of a module. e.g. ``/usr/lib/python3.9/os.py``
  85. """
  86. module = self._get_module_context()
  87. if module.is_stub() or not module.is_compiled():
  88. # Compiled modules should not return a module path even if they
  89. # have one.
  90. path: Optional[Path] = self._get_module_context().py__file__()
  91. return path
  92. return None
  93. @property
  94. def name(self):
  95. """
  96. Name of variable/function/class/module.
  97. For example, for ``x = None`` it returns ``'x'``.
  98. :rtype: str or None
  99. """
  100. return self._name.get_public_name()
  101. @property
  102. def type(self):
  103. """
  104. The type of the definition.
  105. Here is an example of the value of this attribute. Let's consider
  106. the following source. As what is in ``variable`` is unambiguous
  107. to Jedi, :meth:`jedi.Script.infer` should return a list of
  108. definition for ``sys``, ``f``, ``C`` and ``x``.
  109. >>> from jedi import Script
  110. >>> source = '''
  111. ... import keyword
  112. ...
  113. ... class C:
  114. ... pass
  115. ...
  116. ... class D:
  117. ... pass
  118. ...
  119. ... x = D()
  120. ...
  121. ... def f():
  122. ... pass
  123. ...
  124. ... for variable in [keyword, f, C, x]:
  125. ... variable'''
  126. >>> script = Script(source)
  127. >>> defs = script.infer()
  128. Before showing what is in ``defs``, let's sort it by :attr:`line`
  129. so that it is easy to relate the result to the source code.
  130. >>> defs = sorted(defs, key=lambda d: d.line)
  131. >>> print(defs) # doctest: +NORMALIZE_WHITESPACE
  132. [<Name full_name='keyword', description='module keyword'>,
  133. <Name full_name='__main__.C', description='class C'>,
  134. <Name full_name='__main__.D', description='instance D'>,
  135. <Name full_name='__main__.f', description='def f'>]
  136. Finally, here is what you can get from :attr:`type`:
  137. >>> defs = [d.type for d in defs]
  138. >>> defs[0]
  139. 'module'
  140. >>> defs[1]
  141. 'class'
  142. >>> defs[2]
  143. 'instance'
  144. >>> defs[3]
  145. 'function'
  146. Valid values for type are ``module``, ``class``, ``instance``, ``function``,
  147. ``param``, ``path``, ``keyword``, ``property`` and ``statement``.
  148. """
  149. tree_name = self._name.tree_name
  150. resolve = False
  151. if tree_name is not None:
  152. # TODO move this to their respective names.
  153. definition = tree_name.get_definition()
  154. if definition is not None and definition.type == 'import_from' and \
  155. tree_name.is_definition():
  156. resolve = True
  157. if isinstance(self._name, SubModuleName) or resolve:
  158. for value in self._name.infer():
  159. return value.api_type
  160. return self._name.api_type
  161. @property
  162. def module_name(self):
  163. """
  164. The module name, a bit similar to what ``__name__`` is in a random
  165. Python module.
  166. >>> from jedi import Script
  167. >>> source = 'import json'
  168. >>> script = Script(source, path='example.py')
  169. >>> d = script.infer()[0]
  170. >>> print(d.module_name) # doctest: +ELLIPSIS
  171. json
  172. """
  173. return self._get_module_context().py__name__()
  174. def in_builtin_module(self):
  175. """
  176. Returns True, if this is a builtin module.
  177. """
  178. value = self._get_module_context().get_value()
  179. if isinstance(value, StubModuleValue):
  180. return any(v.is_compiled() for v in value.non_stub_value_set)
  181. return value.is_compiled()
  182. @property
  183. def line(self):
  184. """The line where the definition occurs (starting with 1)."""
  185. start_pos = self._name.start_pos
  186. if start_pos is None:
  187. return None
  188. return start_pos[0]
  189. @property
  190. def column(self):
  191. """The column where the definition occurs (starting with 0)."""
  192. start_pos = self._name.start_pos
  193. if start_pos is None:
  194. return None
  195. return start_pos[1]
  196. def get_definition_start_position(self):
  197. """
  198. The (row, column) of the start of the definition range. Rows start with
  199. 1, columns start with 0.
  200. :rtype: Optional[Tuple[int, int]]
  201. """
  202. if self._name.tree_name is None:
  203. return None
  204. definition = self._name.tree_name.get_definition()
  205. if definition is None:
  206. return self._name.start_pos
  207. return definition.start_pos
  208. def get_definition_end_position(self):
  209. """
  210. The (row, column) of the end of the definition range. Rows start with
  211. 1, columns start with 0.
  212. :rtype: Optional[Tuple[int, int]]
  213. """
  214. if self._name.tree_name is None:
  215. return None
  216. definition = self._name.tree_name.get_definition()
  217. if definition is None:
  218. return self._name.tree_name.end_pos
  219. if self.type in ("function", "class"):
  220. last_leaf = definition.get_last_leaf()
  221. if last_leaf.type == "newline":
  222. return last_leaf.get_previous_leaf().end_pos
  223. return last_leaf.end_pos
  224. return definition.end_pos
  225. def docstring(self, raw=False, fast=True):
  226. r"""
  227. Return a document string for this completion object.
  228. Example:
  229. >>> from jedi import Script
  230. >>> source = '''\
  231. ... def f(a, b=1):
  232. ... "Document for function f."
  233. ... '''
  234. >>> script = Script(source, path='example.py')
  235. >>> doc = script.infer(1, len('def f'))[0].docstring()
  236. >>> print(doc)
  237. f(a, b=1)
  238. <BLANKLINE>
  239. Document for function f.
  240. Notice that useful extra information is added to the actual
  241. docstring, e.g. function signatures are prepended to their docstrings.
  242. If you need the actual docstring, use ``raw=True`` instead.
  243. >>> print(script.infer(1, len('def f'))[0].docstring(raw=True))
  244. Document for function f.
  245. :param fast: Don't follow imports that are only one level deep like
  246. ``import foo``, but follow ``from foo import bar``. This makes
  247. sense for speed reasons. Completing `import a` is slow if you use
  248. the ``foo.docstring(fast=False)`` on every object, because it
  249. parses all libraries starting with ``a``.
  250. """
  251. if isinstance(self._name, ImportName) and fast:
  252. return ''
  253. doc = self._get_docstring()
  254. if raw:
  255. return doc
  256. signature_text = self._get_docstring_signature()
  257. if signature_text and doc:
  258. return signature_text + '\n\n' + doc
  259. else:
  260. return signature_text + doc
  261. def _get_docstring(self):
  262. return self._name.py__doc__()
  263. def _get_docstring_signature(self):
  264. return '\n'.join(
  265. signature.to_string()
  266. for signature in self._get_signatures(for_docstring=True)
  267. )
  268. @property
  269. def description(self):
  270. """
  271. A description of the :class:`.Name` object, which is heavily used
  272. in testing. e.g. for ``isinstance`` it returns ``def isinstance``.
  273. Example:
  274. >>> from jedi import Script
  275. >>> source = '''
  276. ... def f():
  277. ... pass
  278. ...
  279. ... class C:
  280. ... pass
  281. ...
  282. ... variable = f if random.choice([0,1]) else C'''
  283. >>> script = Script(source) # line is maximum by default
  284. >>> defs = script.infer(column=3)
  285. >>> defs = sorted(defs, key=lambda d: d.line)
  286. >>> print(defs) # doctest: +NORMALIZE_WHITESPACE
  287. [<Name full_name='__main__.f', description='def f'>,
  288. <Name full_name='__main__.C', description='class C'>]
  289. >>> str(defs[0].description)
  290. 'def f'
  291. >>> str(defs[1].description)
  292. 'class C'
  293. """
  294. typ = self.type
  295. tree_name = self._name.tree_name
  296. if typ == 'param':
  297. return typ + ' ' + self._name.to_string()
  298. if typ in ('function', 'class', 'module', 'instance') or tree_name is None:
  299. if typ == 'function':
  300. # For the description we want a short and a pythonic way.
  301. typ = 'def'
  302. return typ + ' ' + self._name.get_public_name()
  303. definition = tree_name.get_definition(include_setitem=True) or tree_name
  304. # Remove the prefix, because that's not what we want for get_code
  305. # here.
  306. txt = definition.get_code(include_prefix=False)
  307. # Delete comments:
  308. txt = re.sub(r'#[^\n]+\n', ' ', txt)
  309. # Delete multi spaces/newlines
  310. txt = re.sub(r'\s+', ' ', txt).strip()
  311. return txt
  312. @property
  313. def full_name(self):
  314. """
  315. Dot-separated path of this object.
  316. It is in the form of ``<module>[.<submodule>[...]][.<object>]``.
  317. It is useful when you want to look up Python manual of the
  318. object at hand.
  319. Example:
  320. >>> from jedi import Script
  321. >>> source = '''
  322. ... import os
  323. ... os.path.join'''
  324. >>> script = Script(source, path='example.py')
  325. >>> print(script.infer(3, len('os.path.join'))[0].full_name)
  326. os.path.join
  327. Notice that it returns ``'os.path.join'`` instead of (for example)
  328. ``'posixpath.join'``. This is not correct, since the modules name would
  329. be ``<module 'posixpath' ...>```. However most users find the latter
  330. more practical.
  331. """
  332. if not self._name.is_value_name:
  333. return None
  334. names = self._name.get_qualified_names(include_module_names=True)
  335. if names is None:
  336. return None
  337. names = list(names)
  338. try:
  339. names[0] = self._mapping[names[0]]
  340. except KeyError:
  341. pass
  342. return '.'.join(names)
  343. def is_stub(self):
  344. """
  345. Returns True if the current name is defined in a stub file.
  346. """
  347. if not self._name.is_value_name:
  348. return False
  349. return self._name.get_root_context().is_stub()
  350. def is_side_effect(self):
  351. """
  352. Checks if a name is defined as ``self.foo = 3``. In case of self, this
  353. function would return False, for foo it would return True.
  354. """
  355. tree_name = self._name.tree_name
  356. if tree_name is None:
  357. return False
  358. return tree_name.is_definition() and tree_name.parent.type == 'trailer'
  359. @debug.increase_indent_cm('goto on name')
  360. def goto(self, *, follow_imports=False, follow_builtin_imports=False,
  361. only_stubs=False, prefer_stubs=False):
  362. """
  363. Like :meth:`.Script.goto` (also supports the same params), but does it
  364. for the current name. This is typically useful if you are using
  365. something like :meth:`.Script.get_names()`.
  366. :param follow_imports: The goto call will follow imports.
  367. :param follow_builtin_imports: If follow_imports is True will try to
  368. look up names in builtins (i.e. compiled or extension modules).
  369. :param only_stubs: Only return stubs for this goto call.
  370. :param prefer_stubs: Prefer stubs to Python objects for this goto call.
  371. :rtype: list of :class:`Name`
  372. """
  373. if not self._name.is_value_name:
  374. return []
  375. names = self._name.goto()
  376. if follow_imports:
  377. names = filter_follow_imports(names, follow_builtin_imports)
  378. names = convert_names(
  379. names,
  380. only_stubs=only_stubs,
  381. prefer_stubs=prefer_stubs,
  382. )
  383. return [self if n == self._name else Name(self._inference_state, n)
  384. for n in names]
  385. @debug.increase_indent_cm('infer on name')
  386. def infer(self, *, only_stubs=False, prefer_stubs=False):
  387. """
  388. Like :meth:`.Script.infer`, it can be useful to understand which type
  389. the current name has.
  390. Return the actual definitions. I strongly recommend not using it for
  391. your completions, because it might slow down |jedi|. If you want to
  392. read only a few objects (<=20), it might be useful, especially to get
  393. the original docstrings. The basic problem of this function is that it
  394. follows all results. This means with 1000 completions (e.g. numpy),
  395. it's just very, very slow.
  396. :param only_stubs: Only return stubs for this goto call.
  397. :param prefer_stubs: Prefer stubs to Python objects for this type
  398. inference call.
  399. :rtype: list of :class:`Name`
  400. """
  401. assert not (only_stubs and prefer_stubs)
  402. if not self._name.is_value_name:
  403. return []
  404. # First we need to make sure that we have stub names (if possible) that
  405. # we can follow. If we don't do that, we can end up with the inferred
  406. # results of Python objects instead of stubs.
  407. names = convert_names([self._name], prefer_stubs=True)
  408. values = convert_values(
  409. ValueSet.from_sets(n.infer() for n in names),
  410. only_stubs=only_stubs,
  411. prefer_stubs=prefer_stubs,
  412. )
  413. resulting_names = [c.name for c in values]
  414. return [self if n == self._name else Name(self._inference_state, n)
  415. for n in resulting_names]
  416. def parent(self):
  417. """
  418. Returns the parent scope of this identifier.
  419. :rtype: Name
  420. """
  421. if not self._name.is_value_name:
  422. return None
  423. if self.type in ('function', 'class', 'param') and self._name.tree_name is not None:
  424. # Since the parent_context doesn't really match what the user
  425. # thinks of that the parent is here, we do these cases separately.
  426. # The reason for this is the following:
  427. # - class: Nested classes parent_context is always the
  428. # parent_context of the most outer one.
  429. # - function: Functions in classes have the module as
  430. # parent_context.
  431. # - param: The parent_context of a param is not its function but
  432. # e.g. the outer class or module.
  433. cls_or_func_node = self._name.tree_name.get_definition()
  434. parent = search_ancestor(cls_or_func_node, 'funcdef', 'classdef', 'file_input')
  435. context = self._get_module_context().create_value(parent).as_context()
  436. else:
  437. context = self._name.parent_context
  438. if context is None:
  439. return None
  440. while context.name is None:
  441. # Happens for comprehension contexts
  442. context = context.parent_context
  443. return Name(self._inference_state, context.name)
  444. def __repr__(self):
  445. return "<%s %sname=%r, description=%r>" % (
  446. self.__class__.__name__,
  447. 'full_' if self.full_name else '',
  448. self.full_name or self.name,
  449. self.description,
  450. )
  451. def get_line_code(self, before=0, after=0):
  452. """
  453. Returns the line of code where this object was defined.
  454. :param before: Add n lines before the current line to the output.
  455. :param after: Add n lines after the current line to the output.
  456. :return str: Returns the line(s) of code or an empty string if it's a
  457. builtin.
  458. """
  459. if not self._name.is_value_name:
  460. return ''
  461. lines = self._name.get_root_context().code_lines
  462. if lines is None:
  463. # Probably a builtin module, just ignore in that case.
  464. return ''
  465. index = self._name.start_pos[0] - 1
  466. start_index = max(index - before, 0)
  467. return ''.join(lines[start_index:index + after + 1])
  468. def _get_signatures(self, for_docstring=False):
  469. if self._name.api_type == 'property':
  470. return []
  471. if for_docstring and self._name.api_type == 'statement' and not self.is_stub():
  472. # For docstrings we don't resolve signatures if they are simple
  473. # statements and not stubs. This is a speed optimization.
  474. return []
  475. if isinstance(self._name, MixedName):
  476. # While this would eventually happen anyway, it's basically just a
  477. # shortcut to not infer anything tree related, because it's really
  478. # not necessary.
  479. return self._name.infer_compiled_value().get_signatures()
  480. names = convert_names([self._name], prefer_stubs=True)
  481. return [sig for name in names for sig in name.infer().get_signatures()]
  482. def get_signatures(self):
  483. """
  484. Returns all potential signatures for a function or a class. Multiple
  485. signatures are typical if you use Python stubs with ``@overload``.
  486. :rtype: list of :class:`BaseSignature`
  487. """
  488. return [
  489. BaseSignature(self._inference_state, s)
  490. for s in self._get_signatures()
  491. ]
  492. def execute(self):
  493. """
  494. Uses type inference to "execute" this identifier and returns the
  495. executed objects.
  496. :rtype: list of :class:`Name`
  497. """
  498. return _values_to_definitions(self._name.infer().execute_with_values())
  499. def get_type_hint(self):
  500. """
  501. Returns type hints like ``Iterable[int]`` or ``Union[int, str]``.
  502. This method might be quite slow, especially for functions. The problem
  503. is finding executions for those functions to return something like
  504. ``Callable[[int, str], str]``.
  505. :rtype: str
  506. """
  507. return self._name.infer().get_type_hint()
  508. class Completion(BaseName):
  509. """
  510. ``Completion`` objects are returned from :meth:`.Script.complete`. They
  511. provide additional information about a completion.
  512. """
  513. def __init__(self, inference_state, name, stack, like_name_length,
  514. is_fuzzy, cached_name=None):
  515. super().__init__(inference_state, name)
  516. self._like_name_length = like_name_length
  517. self._stack = stack
  518. self._is_fuzzy = is_fuzzy
  519. self._cached_name = cached_name
  520. # Completion objects with the same Completion name (which means
  521. # duplicate items in the completion)
  522. self._same_name_completions = []
  523. def _complete(self, like_name):
  524. append = ''
  525. if settings.add_bracket_after_function \
  526. and self.type == 'function':
  527. append = '('
  528. name = self._name.get_public_name()
  529. if like_name:
  530. name = name[self._like_name_length:]
  531. return name + append
  532. @property
  533. def complete(self):
  534. """
  535. Only works with non-fuzzy completions. Returns None if fuzzy
  536. completions are used.
  537. Return the rest of the word, e.g. completing ``isinstance``::
  538. isinstan# <-- Cursor is here
  539. would return the string 'ce'. It also adds additional stuff, depending
  540. on your ``settings.py``.
  541. Assuming the following function definition::
  542. def foo(param=0):
  543. pass
  544. completing ``foo(par`` would give a ``Completion`` which ``complete``
  545. would be ``am=``.
  546. """
  547. if self._is_fuzzy:
  548. return None
  549. return self._complete(True)
  550. @property
  551. def name_with_symbols(self):
  552. """
  553. Similar to :attr:`.name`, but like :attr:`.name` returns also the
  554. symbols, for example assuming the following function definition::
  555. def foo(param=0):
  556. pass
  557. completing ``foo(`` would give a ``Completion`` which
  558. ``name_with_symbols`` would be "param=".
  559. """
  560. return self._complete(False)
  561. def docstring(self, raw=False, fast=True):
  562. """
  563. Documented under :meth:`BaseName.docstring`.
  564. """
  565. if self._like_name_length >= 3:
  566. # In this case we can just resolve the like name, because we
  567. # wouldn't load like > 100 Python modules anymore.
  568. fast = False
  569. return super().docstring(raw=raw, fast=fast)
  570. def _get_docstring(self):
  571. if self._cached_name is not None:
  572. return completion_cache.get_docstring(
  573. self._cached_name,
  574. self._name.get_public_name(),
  575. lambda: self._get_cache()
  576. )
  577. return super()._get_docstring()
  578. def _get_docstring_signature(self):
  579. if self._cached_name is not None:
  580. return completion_cache.get_docstring_signature(
  581. self._cached_name,
  582. self._name.get_public_name(),
  583. lambda: self._get_cache()
  584. )
  585. return super()._get_docstring_signature()
  586. def _get_cache(self):
  587. return (
  588. super().type,
  589. super()._get_docstring_signature(),
  590. super()._get_docstring(),
  591. )
  592. @property
  593. def type(self):
  594. """
  595. Documented under :meth:`BaseName.type`.
  596. """
  597. # Purely a speed optimization.
  598. if self._cached_name is not None:
  599. return completion_cache.get_type(
  600. self._cached_name,
  601. self._name.get_public_name(),
  602. lambda: self._get_cache()
  603. )
  604. return super().type
  605. def get_completion_prefix_length(self):
  606. """
  607. Returns the length of the prefix being completed.
  608. For example, completing ``isinstance``::
  609. isinstan# <-- Cursor is here
  610. would return 8, because len('isinstan') == 8.
  611. Assuming the following function definition::
  612. def foo(param=0):
  613. pass
  614. completing ``foo(par`` would return 3.
  615. """
  616. return self._like_name_length
  617. def __repr__(self):
  618. return '<%s: %s>' % (type(self).__name__, self._name.get_public_name())
  619. class Name(BaseName):
  620. """
  621. *Name* objects are returned from many different APIs including
  622. :meth:`.Script.goto` or :meth:`.Script.infer`.
  623. """
  624. def __init__(self, inference_state, definition):
  625. super().__init__(inference_state, definition)
  626. @memoize_method
  627. def defined_names(self):
  628. """
  629. List sub-definitions (e.g., methods in class).
  630. :rtype: list of :class:`Name`
  631. """
  632. defs = self._name.infer()
  633. return sorted(
  634. unite(defined_names(self._inference_state, d) for d in defs),
  635. key=lambda s: s._name.start_pos or (0, 0)
  636. )
  637. def is_definition(self):
  638. """
  639. Returns True, if defined as a name in a statement, function or class.
  640. Returns False, if it's a reference to such a definition.
  641. """
  642. if self._name.tree_name is None:
  643. return True
  644. else:
  645. return self._name.tree_name.is_definition()
  646. def __eq__(self, other):
  647. return self._name.start_pos == other._name.start_pos \
  648. and self.module_path == other.module_path \
  649. and self.name == other.name \
  650. and self._inference_state == other._inference_state
  651. def __ne__(self, other):
  652. return not self.__eq__(other)
  653. def __hash__(self):
  654. return hash((self._name.start_pos, self.module_path, self.name, self._inference_state))
  655. class BaseSignature(Name):
  656. """
  657. These signatures are returned by :meth:`BaseName.get_signatures`
  658. calls.
  659. """
  660. def __init__(self, inference_state, signature):
  661. super().__init__(inference_state, signature.name)
  662. self._signature = signature
  663. @property
  664. def params(self):
  665. """
  666. Returns definitions for all parameters that a signature defines.
  667. This includes stuff like ``*args`` and ``**kwargs``.
  668. :rtype: list of :class:`.ParamName`
  669. """
  670. return [ParamName(self._inference_state, n)
  671. for n in self._signature.get_param_names(resolve_stars=True)]
  672. def to_string(self):
  673. """
  674. Returns a text representation of the signature. This could for example
  675. look like ``foo(bar, baz: int, **kwargs)``.
  676. :rtype: str
  677. """
  678. return self._signature.to_string()
  679. class Signature(BaseSignature):
  680. """
  681. A full signature object is the return value of
  682. :meth:`.Script.get_signatures`.
  683. """
  684. def __init__(self, inference_state, signature, call_details):
  685. super().__init__(inference_state, signature)
  686. self._call_details = call_details
  687. self._signature = signature
  688. @property
  689. def index(self):
  690. """
  691. Returns the param index of the current cursor position.
  692. Returns None if the index cannot be found in the curent call.
  693. :rtype: int
  694. """
  695. return self._call_details.calculate_index(
  696. self._signature.get_param_names(resolve_stars=True)
  697. )
  698. @property
  699. def bracket_start(self):
  700. """
  701. Returns a line/column tuple of the bracket that is responsible for the
  702. last function call. The first line is 1 and the first column 0.
  703. :rtype: int, int
  704. """
  705. return self._call_details.bracket_leaf.start_pos
  706. def __repr__(self):
  707. return '<%s: index=%r %s>' % (
  708. type(self).__name__,
  709. self.index,
  710. self._signature.to_string(),
  711. )
  712. class ParamName(Name):
  713. def infer_default(self):
  714. """
  715. Returns default values like the ``1`` of ``def foo(x=1):``.
  716. :rtype: list of :class:`.Name`
  717. """
  718. return _values_to_definitions(self._name.infer_default())
  719. def infer_annotation(self, **kwargs):
  720. """
  721. :param execute_annotation: Default True; If False, values are not
  722. executed and classes are returned instead of instances.
  723. :rtype: list of :class:`.Name`
  724. """
  725. return _values_to_definitions(self._name.infer_annotation(ignore_stars=True, **kwargs))
  726. def to_string(self):
  727. """
  728. Returns a simple representation of a param, like
  729. ``f: Callable[..., Any]``.
  730. :rtype: str
  731. """
  732. return self._name.to_string()
  733. @property
  734. def kind(self):
  735. """
  736. Returns an enum instance of :mod:`inspect`'s ``Parameter`` enum.
  737. :rtype: :py:attr:`inspect.Parameter.kind`
  738. """
  739. return self._name.get_kind()