Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/jedi/api/classes.py: 33%

304 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-03-26 06:07 +0000

1""" 

2There are a couple of classes documented in here: 

3 

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 

12 

13These classes are the much biggest part of the API, because they contain 

14the interesting information about all operations. 

15""" 

16import re 

17from pathlib import Path 

18from typing import Optional 

19 

20from parso.tree import search_ancestor 

21 

22from jedi import settings 

23from jedi import debug 

24from jedi.inference.utils import unite 

25from jedi.cache import memoize_method 

26from jedi.inference.compiled.mixed import MixedName 

27from jedi.inference.names import ImportName, SubModuleName 

28from jedi.inference.gradual.stub_value import StubModuleValue 

29from jedi.inference.gradual.conversion import convert_names, convert_values 

30from jedi.inference.base_value import ValueSet, HasNoContext 

31from jedi.api.keywords import KeywordName 

32from jedi.api import completion_cache 

33from jedi.api.helpers import filter_follow_imports 

34 

35 

36def _sort_names_by_start_pos(names): 

37 return sorted(names, key=lambda s: s.start_pos or (0, 0)) 

38 

39 

40def defined_names(inference_state, value): 

41 """ 

42 List sub-definitions (e.g., methods in class). 

43 

44 :type scope: Scope 

45 :rtype: list of Name 

46 """ 

47 try: 

48 context = value.as_context() 

49 except HasNoContext: 

50 return [] 

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)] 

54 

55 

56def _values_to_definitions(values): 

57 return [Name(c.inference_state, c.name) for c in values] 

58 

59 

60class BaseName: 

61 """ 

62 The base class for all definitions, completions and signatures. 

63 """ 

64 _mapping = { 

65 'posixpath': 'os.path', 

66 'riscospath': 'os.path', 

67 'ntpath': 'os.path', 

68 'os2emxpath': 'os.path', 

69 'macpath': 'os.path', 

70 'genericpath': 'os.path', 

71 'posix': 'os', 

72 '_io': 'io', 

73 '_functools': 'functools', 

74 '_collections': 'collections', 

75 '_socket': 'socket', 

76 '_sqlite3': 'sqlite3', 

77 } 

78 

79 _tuple_mapping = dict((tuple(k.split('.')), v) for (k, v) in { 

80 'argparse._ActionsContainer': 'argparse.ArgumentParser', 

81 }.items()) 

82 

83 def __init__(self, inference_state, name): 

84 self._inference_state = inference_state 

85 self._name = name 

86 """ 

87 An instance of :class:`parso.python.tree.Name` subclass. 

88 """ 

89 self.is_keyword = isinstance(self._name, KeywordName) 

90 

91 @memoize_method 

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() 

97 

98 @property 

99 def module_path(self) -> Optional[Path]: 

100 """ 

101 Shows the file path of a module. e.g. ``/usr/lib/python3.9/os.py`` 

102 """ 

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 

106 # have one. 

107 path: Optional[Path] = self._get_module_context().py__file__() 

108 if path is not None: 

109 return path 

110 

111 return None 

112 

113 @property 

114 def name(self): 

115 """ 

116 Name of variable/function/class/module. 

117 

118 For example, for ``x = None`` it returns ``'x'``. 

119 

120 :rtype: str or None 

121 """ 

122 return self._name.get_public_name() 

123 

124 @property 

125 def type(self): 

126 """ 

127 The type of the definition. 

128 

129 Here is an example of the value of this attribute. Let's consider 

130 the following source. As what is in ``variable`` is unambiguous 

131 to Jedi, :meth:`jedi.Script.infer` should return a list of 

132 definition for ``sys``, ``f``, ``C`` and ``x``. 

133 

134 >>> from jedi import Script 

135 >>> source = ''' 

136 ... import keyword 

137 ... 

138 ... class C: 

139 ... pass 

140 ... 

141 ... class D: 

142 ... pass 

143 ... 

144 ... x = D() 

145 ... 

146 ... def f(): 

147 ... pass 

148 ... 

149 ... for variable in [keyword, f, C, x]: 

150 ... variable''' 

151 

152 >>> script = Script(source) 

153 >>> defs = script.infer() 

154 

155 Before showing what is in ``defs``, let's sort it by :attr:`line` 

156 so that it is easy to relate the result to the source code. 

157 

158 >>> defs = sorted(defs, key=lambda d: d.line) 

159 >>> print(defs) # doctest: +NORMALIZE_WHITESPACE 

160 [<Name full_name='keyword', description='module keyword'>, 

161 <Name full_name='__main__.C', description='class C'>, 

162 <Name full_name='__main__.D', description='instance D'>, 

163 <Name full_name='__main__.f', description='def f'>] 

164 

165 Finally, here is what you can get from :attr:`type`: 

166 

167 >>> defs = [d.type for d in defs] 

168 >>> defs[0] 

169 'module' 

170 >>> defs[1] 

171 'class' 

172 >>> defs[2] 

173 'instance' 

174 >>> defs[3] 

175 'function' 

176 

177 Valid values for type are ``module``, ``class``, ``instance``, ``function``, 

178 ``param``, ``path``, ``keyword``, ``property`` and ``statement``. 

179 

180 """ 

181 tree_name = self._name.tree_name 

182 resolve = False 

183 if tree_name is not None: 

184 # TODO move this to their respective names. 

185 definition = tree_name.get_definition() 

186 if definition is not None and definition.type == 'import_from' and \ 

187 tree_name.is_definition(): 

188 resolve = True 

189 

190 if isinstance(self._name, SubModuleName) or resolve: 

191 for value in self._name.infer(): 

192 return value.api_type 

193 return self._name.api_type 

194 

195 @property 

196 def module_name(self): 

197 """ 

198 The module name, a bit similar to what ``__name__`` is in a random 

199 Python module. 

200 

201 >>> from jedi import Script 

202 >>> source = 'import json' 

203 >>> script = Script(source, path='example.py') 

204 >>> d = script.infer()[0] 

205 >>> print(d.module_name) # doctest: +ELLIPSIS 

206 json 

207 """ 

208 return self._get_module_context().py__name__() 

209 

210 def in_builtin_module(self): 

211 """ 

212 Returns True, if this is a builtin module. 

213 """ 

214 value = self._get_module_context().get_value() 

215 if isinstance(value, StubModuleValue): 

216 return any(v.is_compiled() for v in value.non_stub_value_set) 

217 return value.is_compiled() 

218 

219 @property 

220 def line(self): 

221 """The line where the definition occurs (starting with 1).""" 

222 start_pos = self._name.start_pos 

223 if start_pos is None: 

224 return None 

225 return start_pos[0] 

226 

227 @property 

228 def column(self): 

229 """The column where the definition occurs (starting with 0).""" 

230 start_pos = self._name.start_pos 

231 if start_pos is None: 

232 return None 

233 return start_pos[1] 

234 

235 def get_definition_start_position(self): 

236 """ 

237 The (row, column) of the start of the definition range. Rows start with 

238 1, columns start with 0. 

239 

240 :rtype: Optional[Tuple[int, int]] 

241 """ 

242 if self._name.tree_name is None: 

243 return None 

244 definition = self._name.tree_name.get_definition() 

245 if definition is None: 

246 return self._name.start_pos 

247 return definition.start_pos 

248 

249 def get_definition_end_position(self): 

250 """ 

251 The (row, column) of the end of the definition range. Rows start with 

252 1, columns start with 0. 

253 

254 :rtype: Optional[Tuple[int, int]] 

255 """ 

256 if self._name.tree_name is None: 

257 return None 

258 definition = self._name.tree_name.get_definition() 

259 if definition is None: 

260 return self._name.tree_name.end_pos 

261 if self.type in ("function", "class"): 

262 last_leaf = definition.get_last_leaf() 

263 if last_leaf.type == "newline": 

264 return last_leaf.get_previous_leaf().end_pos 

265 return last_leaf.end_pos 

266 return definition.end_pos 

267 

268 def docstring(self, raw=False, fast=True): 

269 r""" 

270 Return a document string for this completion object. 

271 

272 Example: 

273 

274 >>> from jedi import Script 

275 >>> source = '''\ 

276 ... def f(a, b=1): 

277 ... "Document for function f." 

278 ... ''' 

279 >>> script = Script(source, path='example.py') 

280 >>> doc = script.infer(1, len('def f'))[0].docstring() 

281 >>> print(doc) 

282 f(a, b=1) 

283 <BLANKLINE> 

284 Document for function f. 

285 

286 Notice that useful extra information is added to the actual 

287 docstring, e.g. function signatures are prepended to their docstrings. 

288 If you need the actual docstring, use ``raw=True`` instead. 

289 

290 >>> print(script.infer(1, len('def f'))[0].docstring(raw=True)) 

291 Document for function f. 

292 

293 :param fast: Don't follow imports that are only one level deep like 

294 ``import foo``, but follow ``from foo import bar``. This makes 

295 sense for speed reasons. Completing `import a` is slow if you use 

296 the ``foo.docstring(fast=False)`` on every object, because it 

297 parses all libraries starting with ``a``. 

298 """ 

299 if isinstance(self._name, ImportName) and fast: 

300 return '' 

301 doc = self._get_docstring() 

302 if raw: 

303 return doc 

304 

305 signature_text = self._get_docstring_signature() 

306 if signature_text and doc: 

307 return signature_text + '\n\n' + doc 

308 else: 

309 return signature_text + doc 

310 

311 def _get_docstring(self): 

312 return self._name.py__doc__() 

313 

314 def _get_docstring_signature(self): 

315 return '\n'.join( 

316 signature.to_string() 

317 for signature in self._get_signatures(for_docstring=True) 

318 ) 

319 

320 @property 

321 def description(self): 

322 """ 

323 A description of the :class:`.Name` object, which is heavily used 

324 in testing. e.g. for ``isinstance`` it returns ``def isinstance``. 

325 

326 Example: 

327 

328 >>> from jedi import Script 

329 >>> source = ''' 

330 ... def f(): 

331 ... pass 

332 ... 

333 ... class C: 

334 ... pass 

335 ... 

336 ... variable = f if random.choice([0,1]) else C''' 

337 >>> script = Script(source) # line is maximum by default 

338 >>> defs = script.infer(column=3) 

339 >>> defs = sorted(defs, key=lambda d: d.line) 

340 >>> print(defs) # doctest: +NORMALIZE_WHITESPACE 

341 [<Name full_name='__main__.f', description='def f'>, 

342 <Name full_name='__main__.C', description='class C'>] 

343 >>> str(defs[0].description) 

344 'def f' 

345 >>> str(defs[1].description) 

346 'class C' 

347 

348 """ 

349 typ = self.type 

350 tree_name = self._name.tree_name 

351 if typ == 'param': 

352 return typ + ' ' + self._name.to_string() 

353 if typ in ('function', 'class', 'module', 'instance') or tree_name is None: 

354 if typ == 'function': 

355 # For the description we want a short and a pythonic way. 

356 typ = 'def' 

357 return typ + ' ' + self._name.get_public_name() 

358 

359 definition = tree_name.get_definition(include_setitem=True) or tree_name 

360 # Remove the prefix, because that's not what we want for get_code 

361 # here. 

362 txt = definition.get_code(include_prefix=False) 

363 # Delete comments: 

364 txt = re.sub(r'#[^\n]+\n', ' ', txt) 

365 # Delete multi spaces/newlines 

366 txt = re.sub(r'\s+', ' ', txt).strip() 

367 return txt 

368 

369 @property 

370 def full_name(self): 

371 """ 

372 Dot-separated path of this object. 

373 

374 It is in the form of ``<module>[.<submodule>[...]][.<object>]``. 

375 It is useful when you want to look up Python manual of the 

376 object at hand. 

377 

378 Example: 

379 

380 >>> from jedi import Script 

381 >>> source = ''' 

382 ... import os 

383 ... os.path.join''' 

384 >>> script = Script(source, path='example.py') 

385 >>> print(script.infer(3, len('os.path.join'))[0].full_name) 

386 os.path.join 

387 

388 Notice that it returns ``'os.path.join'`` instead of (for example) 

389 ``'posixpath.join'``. This is not correct, since the modules name would 

390 be ``<module 'posixpath' ...>```. However most users find the latter 

391 more practical. 

392 """ 

393 if not self._name.is_value_name: 

394 return None 

395 

396 names = self._name.get_qualified_names(include_module_names=True) 

397 if names is None: 

398 return None 

399 

400 names = list(names) 

401 try: 

402 names[0] = self._mapping[names[0]] 

403 except KeyError: 

404 pass 

405 

406 return '.'.join(names) 

407 

408 def is_stub(self): 

409 """ 

410 Returns True if the current name is defined in a stub file. 

411 """ 

412 if not self._name.is_value_name: 

413 return False 

414 

415 return self._name.get_root_context().is_stub() 

416 

417 def is_side_effect(self): 

418 """ 

419 Checks if a name is defined as ``self.foo = 3``. In case of self, this 

420 function would return False, for foo it would return True. 

421 """ 

422 tree_name = self._name.tree_name 

423 if tree_name is None: 

424 return False 

425 return tree_name.is_definition() and tree_name.parent.type == 'trailer' 

426 

427 @debug.increase_indent_cm('goto on name') 

428 def goto(self, *, follow_imports=False, follow_builtin_imports=False, 

429 only_stubs=False, prefer_stubs=False): 

430 

431 """ 

432 Like :meth:`.Script.goto` (also supports the same params), but does it 

433 for the current name. This is typically useful if you are using 

434 something like :meth:`.Script.get_names()`. 

435 

436 :param follow_imports: The goto call will follow imports. 

437 :param follow_builtin_imports: If follow_imports is True will try to 

438 look up names in builtins (i.e. compiled or extension modules). 

439 :param only_stubs: Only return stubs for this goto call. 

440 :param prefer_stubs: Prefer stubs to Python objects for this goto call. 

441 :rtype: list of :class:`Name` 

442 """ 

443 if not self._name.is_value_name: 

444 return [] 

445 

446 names = self._name.goto() 

447 if follow_imports: 

448 names = filter_follow_imports(names, follow_builtin_imports) 

449 names = convert_names( 

450 names, 

451 only_stubs=only_stubs, 

452 prefer_stubs=prefer_stubs, 

453 ) 

454 return [self if n == self._name else Name(self._inference_state, n) 

455 for n in names] 

456 

457 @debug.increase_indent_cm('infer on name') 

458 def infer(self, *, only_stubs=False, prefer_stubs=False): 

459 """ 

460 Like :meth:`.Script.infer`, it can be useful to understand which type 

461 the current name has. 

462 

463 Return the actual definitions. I strongly recommend not using it for 

464 your completions, because it might slow down |jedi|. If you want to 

465 read only a few objects (<=20), it might be useful, especially to get 

466 the original docstrings. The basic problem of this function is that it 

467 follows all results. This means with 1000 completions (e.g. numpy), 

468 it's just very, very slow. 

469 

470 :param only_stubs: Only return stubs for this goto call. 

471 :param prefer_stubs: Prefer stubs to Python objects for this type 

472 inference call. 

473 :rtype: list of :class:`Name` 

474 """ 

475 assert not (only_stubs and prefer_stubs) 

476 

477 if not self._name.is_value_name: 

478 return [] 

479 

480 # First we need to make sure that we have stub names (if possible) that 

481 # we can follow. If we don't do that, we can end up with the inferred 

482 # results of Python objects instead of stubs. 

483 names = convert_names([self._name], prefer_stubs=True) 

484 values = convert_values( 

485 ValueSet.from_sets(n.infer() for n in names), 

486 only_stubs=only_stubs, 

487 prefer_stubs=prefer_stubs, 

488 ) 

489 resulting_names = [c.name for c in values] 

490 return [self if n == self._name else Name(self._inference_state, n) 

491 for n in resulting_names] 

492 

493 def parent(self): 

494 """ 

495 Returns the parent scope of this identifier. 

496 

497 :rtype: Name 

498 """ 

499 if not self._name.is_value_name: 

500 return None 

501 

502 if self.type in ('function', 'class', 'param') and self._name.tree_name is not None: 

503 # Since the parent_context doesn't really match what the user 

504 # thinks of that the parent is here, we do these cases separately. 

505 # The reason for this is the following: 

506 # - class: Nested classes parent_context is always the 

507 # parent_context of the most outer one. 

508 # - function: Functions in classes have the module as 

509 # parent_context. 

510 # - param: The parent_context of a param is not its function but 

511 # e.g. the outer class or module. 

512 cls_or_func_node = self._name.tree_name.get_definition() 

513 parent = search_ancestor(cls_or_func_node, 'funcdef', 'classdef', 'file_input') 

514 context = self._get_module_context().create_value(parent).as_context() 

515 else: 

516 context = self._name.parent_context 

517 

518 if context is None: 

519 return None 

520 while context.name is None: 

521 # Happens for comprehension contexts 

522 context = context.parent_context 

523 

524 return Name(self._inference_state, context.name) 

525 

526 def __repr__(self): 

527 return "<%s %sname=%r, description=%r>" % ( 

528 self.__class__.__name__, 

529 'full_' if self.full_name else '', 

530 self.full_name or self.name, 

531 self.description, 

532 ) 

533 

534 def get_line_code(self, before=0, after=0): 

535 """ 

536 Returns the line of code where this object was defined. 

537 

538 :param before: Add n lines before the current line to the output. 

539 :param after: Add n lines after the current line to the output. 

540 

541 :return str: Returns the line(s) of code or an empty string if it's a 

542 builtin. 

543 """ 

544 if not self._name.is_value_name: 

545 return '' 

546 

547 lines = self._name.get_root_context().code_lines 

548 if lines is None: 

549 # Probably a builtin module, just ignore in that case. 

550 return '' 

551 

552 index = self._name.start_pos[0] - 1 

553 start_index = max(index - before, 0) 

554 return ''.join(lines[start_index:index + after + 1]) 

555 

556 def _get_signatures(self, for_docstring=False): 

557 if self._name.api_type == 'property': 

558 return [] 

559 if for_docstring and self._name.api_type == 'statement' and not self.is_stub(): 

560 # For docstrings we don't resolve signatures if they are simple 

561 # statements and not stubs. This is a speed optimization. 

562 return [] 

563 

564 if isinstance(self._name, MixedName): 

565 # While this would eventually happen anyway, it's basically just a 

566 # shortcut to not infer anything tree related, because it's really 

567 # not necessary. 

568 return self._name.infer_compiled_value().get_signatures() 

569 

570 names = convert_names([self._name], prefer_stubs=True) 

571 return [sig for name in names for sig in name.infer().get_signatures()] 

572 

573 def get_signatures(self): 

574 """ 

575 Returns all potential signatures for a function or a class. Multiple 

576 signatures are typical if you use Python stubs with ``@overload``. 

577 

578 :rtype: list of :class:`BaseSignature` 

579 """ 

580 return [ 

581 BaseSignature(self._inference_state, s) 

582 for s in self._get_signatures() 

583 ] 

584 

585 def execute(self): 

586 """ 

587 Uses type inference to "execute" this identifier and returns the 

588 executed objects. 

589 

590 :rtype: list of :class:`Name` 

591 """ 

592 return _values_to_definitions(self._name.infer().execute_with_values()) 

593 

594 def get_type_hint(self): 

595 """ 

596 Returns type hints like ``Iterable[int]`` or ``Union[int, str]``. 

597 

598 This method might be quite slow, especially for functions. The problem 

599 is finding executions for those functions to return something like 

600 ``Callable[[int, str], str]``. 

601 

602 :rtype: str 

603 """ 

604 return self._name.infer().get_type_hint() 

605 

606 

607class Completion(BaseName): 

608 """ 

609 ``Completion`` objects are returned from :meth:`.Script.complete`. They 

610 provide additional information about a completion. 

611 """ 

612 def __init__(self, inference_state, name, stack, like_name_length, 

613 is_fuzzy, cached_name=None): 

614 super().__init__(inference_state, name) 

615 

616 self._like_name_length = like_name_length 

617 self._stack = stack 

618 self._is_fuzzy = is_fuzzy 

619 self._cached_name = cached_name 

620 

621 # Completion objects with the same Completion name (which means 

622 # duplicate items in the completion) 

623 self._same_name_completions = [] 

624 

625 def _complete(self, like_name): 

626 append = '' 

627 if settings.add_bracket_after_function \ 

628 and self.type == 'function': 

629 append = '(' 

630 

631 name = self._name.get_public_name() 

632 if like_name: 

633 name = name[self._like_name_length:] 

634 return name + append 

635 

636 @property 

637 def complete(self): 

638 """ 

639 Only works with non-fuzzy completions. Returns None if fuzzy 

640 completions are used. 

641 

642 Return the rest of the word, e.g. completing ``isinstance``:: 

643 

644 isinstan# <-- Cursor is here 

645 

646 would return the string 'ce'. It also adds additional stuff, depending 

647 on your ``settings.py``. 

648 

649 Assuming the following function definition:: 

650 

651 def foo(param=0): 

652 pass 

653 

654 completing ``foo(par`` would give a ``Completion`` which ``complete`` 

655 would be ``am=``. 

656 """ 

657 if self._is_fuzzy: 

658 return None 

659 return self._complete(True) 

660 

661 @property 

662 def name_with_symbols(self): 

663 """ 

664 Similar to :attr:`.name`, but like :attr:`.name` returns also the 

665 symbols, for example assuming the following function definition:: 

666 

667 def foo(param=0): 

668 pass 

669 

670 completing ``foo(`` would give a ``Completion`` which 

671 ``name_with_symbols`` would be "param=". 

672 

673 """ 

674 return self._complete(False) 

675 

676 def docstring(self, raw=False, fast=True): 

677 """ 

678 Documented under :meth:`BaseName.docstring`. 

679 """ 

680 if self._like_name_length >= 3: 

681 # In this case we can just resolve the like name, because we 

682 # wouldn't load like > 100 Python modules anymore. 

683 fast = False 

684 

685 return super().docstring(raw=raw, fast=fast) 

686 

687 def _get_docstring(self): 

688 if self._cached_name is not None: 

689 return completion_cache.get_docstring( 

690 self._cached_name, 

691 self._name.get_public_name(), 

692 lambda: self._get_cache() 

693 ) 

694 return super()._get_docstring() 

695 

696 def _get_docstring_signature(self): 

697 if self._cached_name is not None: 

698 return completion_cache.get_docstring_signature( 

699 self._cached_name, 

700 self._name.get_public_name(), 

701 lambda: self._get_cache() 

702 ) 

703 return super()._get_docstring_signature() 

704 

705 def _get_cache(self): 

706 return ( 

707 super().type, 

708 super()._get_docstring_signature(), 

709 super()._get_docstring(), 

710 ) 

711 

712 @property 

713 def type(self): 

714 """ 

715 Documented under :meth:`BaseName.type`. 

716 """ 

717 # Purely a speed optimization. 

718 if self._cached_name is not None: 

719 return completion_cache.get_type( 

720 self._cached_name, 

721 self._name.get_public_name(), 

722 lambda: self._get_cache() 

723 ) 

724 

725 return super().type 

726 

727 def get_completion_prefix_length(self): 

728 """ 

729 Returns the length of the prefix being completed. 

730 For example, completing ``isinstance``:: 

731 

732 isinstan# <-- Cursor is here 

733 

734 would return 8, because len('isinstan') == 8. 

735 

736 Assuming the following function definition:: 

737 

738 def foo(param=0): 

739 pass 

740 

741 completing ``foo(par`` would return 3. 

742 """ 

743 return self._like_name_length 

744 

745 def __repr__(self): 

746 return '<%s: %s>' % (type(self).__name__, self._name.get_public_name()) 

747 

748 

749class Name(BaseName): 

750 """ 

751 *Name* objects are returned from many different APIs including 

752 :meth:`.Script.goto` or :meth:`.Script.infer`. 

753 """ 

754 def __init__(self, inference_state, definition): 

755 super().__init__(inference_state, definition) 

756 

757 @memoize_method 

758 def defined_names(self): 

759 """ 

760 List sub-definitions (e.g., methods in class). 

761 

762 :rtype: list of :class:`Name` 

763 """ 

764 defs = self._name.infer() 

765 return sorted( 

766 unite(defined_names(self._inference_state, d) for d in defs), 

767 key=lambda s: s._name.start_pos or (0, 0) 

768 ) 

769 

770 def is_definition(self): 

771 """ 

772 Returns True, if defined as a name in a statement, function or class. 

773 Returns False, if it's a reference to such a definition. 

774 """ 

775 if self._name.tree_name is None: 

776 return True 

777 else: 

778 return self._name.tree_name.is_definition() 

779 

780 def __eq__(self, other): 

781 return self._name.start_pos == other._name.start_pos \ 

782 and self.module_path == other.module_path \ 

783 and self.name == other.name \ 

784 and self._inference_state == other._inference_state 

785 

786 def __ne__(self, other): 

787 return not self.__eq__(other) 

788 

789 def __hash__(self): 

790 return hash((self._name.start_pos, self.module_path, self.name, self._inference_state)) 

791 

792 

793class BaseSignature(Name): 

794 """ 

795 These signatures are returned by :meth:`BaseName.get_signatures` 

796 calls. 

797 """ 

798 def __init__(self, inference_state, signature): 

799 super().__init__(inference_state, signature.name) 

800 self._signature = signature 

801 

802 @property 

803 def params(self): 

804 """ 

805 Returns definitions for all parameters that a signature defines. 

806 This includes stuff like ``*args`` and ``**kwargs``. 

807 

808 :rtype: list of :class:`.ParamName` 

809 """ 

810 return [ParamName(self._inference_state, n) 

811 for n in self._signature.get_param_names(resolve_stars=True)] 

812 

813 def to_string(self): 

814 """ 

815 Returns a text representation of the signature. This could for example 

816 look like ``foo(bar, baz: int, **kwargs)``. 

817 

818 :rtype: str 

819 """ 

820 return self._signature.to_string() 

821 

822 

823class Signature(BaseSignature): 

824 """ 

825 A full signature object is the return value of 

826 :meth:`.Script.get_signatures`. 

827 """ 

828 def __init__(self, inference_state, signature, call_details): 

829 super().__init__(inference_state, signature) 

830 self._call_details = call_details 

831 self._signature = signature 

832 

833 @property 

834 def index(self): 

835 """ 

836 Returns the param index of the current cursor position. 

837 Returns None if the index cannot be found in the curent call. 

838 

839 :rtype: int 

840 """ 

841 return self._call_details.calculate_index( 

842 self._signature.get_param_names(resolve_stars=True) 

843 ) 

844 

845 @property 

846 def bracket_start(self): 

847 """ 

848 Returns a line/column tuple of the bracket that is responsible for the 

849 last function call. The first line is 1 and the first column 0. 

850 

851 :rtype: int, int 

852 """ 

853 return self._call_details.bracket_leaf.start_pos 

854 

855 def __repr__(self): 

856 return '<%s: index=%r %s>' % ( 

857 type(self).__name__, 

858 self.index, 

859 self._signature.to_string(), 

860 ) 

861 

862 

863class ParamName(Name): 

864 def infer_default(self): 

865 """ 

866 Returns default values like the ``1`` of ``def foo(x=1):``. 

867 

868 :rtype: list of :class:`.Name` 

869 """ 

870 return _values_to_definitions(self._name.infer_default()) 

871 

872 def infer_annotation(self, **kwargs): 

873 """ 

874 :param execute_annotation: Default True; If False, values are not 

875 executed and classes are returned instead of instances. 

876 :rtype: list of :class:`.Name` 

877 """ 

878 return _values_to_definitions(self._name.infer_annotation(ignore_stars=True, **kwargs)) 

879 

880 def to_string(self): 

881 """ 

882 Returns a simple representation of a param, like 

883 ``f: Callable[..., Any]``. 

884 

885 :rtype: str 

886 """ 

887 return self._name.to_string() 

888 

889 @property 

890 def kind(self): 

891 """ 

892 Returns an enum instance of :mod:`inspect`'s ``Parameter`` enum. 

893 

894 :rtype: :py:attr:`inspect.Parameter.kind` 

895 """ 

896 return self._name.get_kind()