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

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

304 statements  

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 jedi import settings 

21from jedi import debug 

22from jedi.inference.utils import unite 

23from jedi.cache import memoize_method 

24from jedi.inference.compiled.mixed import MixedName 

25from jedi.inference.names import ImportName, SubModuleName 

26from jedi.inference.gradual.stub_value import StubModuleValue 

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

28from jedi.inference.base_value import ValueSet, HasNoContext 

29from jedi.api.keywords import KeywordName 

30from jedi.api import completion_cache 

31from jedi.api.helpers import filter_follow_imports 

32 

33 

34def _sort_names_by_start_pos(names): 

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

36 

37 

38def defined_names(inference_state, value): 

39 """ 

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

41 

42 :type scope: Scope 

43 :rtype: list of Name 

44 """ 

45 try: 

46 context = value.as_context() 

47 except HasNoContext: 

48 return [] 

49 filter = next(context.get_filters()) 

50 names = [name for name in filter.values()] 

51 return [Name(inference_state, n) for n in _sort_names_by_start_pos(names)] 

52 

53 

54def _values_to_definitions(values): 

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

56 

57 

58class BaseName: 

59 """ 

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

61 """ 

62 _mapping = { 

63 'posixpath': 'os.path', 

64 'riscospath': 'os.path', 

65 'ntpath': 'os.path', 

66 'os2emxpath': 'os.path', 

67 'macpath': 'os.path', 

68 'genericpath': 'os.path', 

69 'posix': 'os', 

70 '_io': 'io', 

71 '_functools': 'functools', 

72 '_collections': 'collections', 

73 '_socket': 'socket', 

74 '_sqlite3': 'sqlite3', 

75 } 

76 

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

78 'argparse._ActionsContainer': 'argparse.ArgumentParser', 

79 }.items()) 

80 

81 def __init__(self, inference_state, name): 

82 self._inference_state = inference_state 

83 self._name = name 

84 """ 

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

86 """ 

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

88 

89 @memoize_method 

90 def _get_module_context(self): 

91 # This can take a while to complete, because in the worst case of 

92 # imports (consider `import a` completions), we need to load all 

93 # modules starting with a first. 

94 return self._name.get_root_context() 

95 

96 @property 

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

98 """ 

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

100 """ 

101 module = self._get_module_context() 

102 if module.is_stub() or not module.is_compiled(): 

103 # Compiled modules should not return a module path even if they 

104 # have one. 

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

106 return path 

107 

108 return None 

109 

110 @property 

111 def name(self): 

112 """ 

113 Name of variable/function/class/module. 

114 

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

116 

117 :rtype: str or None 

118 """ 

119 return self._name.get_public_name() 

120 

121 @property 

122 def type(self): 

123 """ 

124 The type of the definition. 

125 

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

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

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

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

130 

131 >>> from jedi import Script 

132 >>> source = ''' 

133 ... import keyword 

134 ... 

135 ... class C: 

136 ... pass 

137 ... 

138 ... class D: 

139 ... pass 

140 ... 

141 ... x = D() 

142 ... 

143 ... def f(): 

144 ... pass 

145 ... 

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

147 ... variable''' 

148 

149 >>> script = Script(source) 

150 >>> defs = script.infer() 

151 

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

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

154 

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

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

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

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

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

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

161 

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

163 

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

165 >>> defs[0] 

166 'module' 

167 >>> defs[1] 

168 'class' 

169 >>> defs[2] 

170 'instance' 

171 >>> defs[3] 

172 'function' 

173 

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

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

176 

177 """ 

178 tree_name = self._name.tree_name 

179 resolve = False 

180 if tree_name is not None: 

181 # TODO move this to their respective names. 

182 definition = tree_name.get_definition() 

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

184 tree_name.is_definition(): 

185 resolve = True 

186 

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

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

189 return value.api_type 

190 return self._name.api_type 

191 

192 @property 

193 def module_name(self): 

194 """ 

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

196 Python module. 

197 

198 >>> from jedi import Script 

199 >>> source = 'import json' 

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

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

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

203 json 

204 """ 

205 return self._get_module_context().py__name__() 

206 

207 def in_builtin_module(self): 

208 """ 

209 Returns True, if this is a builtin module. 

210 """ 

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

212 if isinstance(value, StubModuleValue): 

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

214 return value.is_compiled() 

215 

216 @property 

217 def line(self): 

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

219 start_pos = self._name.start_pos 

220 if start_pos is None: 

221 return None 

222 return start_pos[0] 

223 

224 @property 

225 def column(self): 

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

227 start_pos = self._name.start_pos 

228 if start_pos is None: 

229 return None 

230 return start_pos[1] 

231 

232 def get_definition_start_position(self): 

233 """ 

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

235 1, columns start with 0. 

236 

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

238 """ 

239 if self._name.tree_name is None: 

240 return None 

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

242 if definition is None: 

243 return self._name.start_pos 

244 return definition.start_pos 

245 

246 def get_definition_end_position(self): 

247 """ 

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

249 1, columns start with 0. 

250 

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

252 """ 

253 if self._name.tree_name is None: 

254 return None 

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

256 if definition is None: 

257 return self._name.tree_name.end_pos 

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

259 last_leaf = definition.get_last_leaf() 

260 if last_leaf.type == "newline": 

261 return last_leaf.get_previous_leaf().end_pos 

262 return last_leaf.end_pos 

263 return definition.end_pos 

264 

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

266 r""" 

267 Return a document string for this completion object. 

268 

269 Example: 

270 

271 >>> from jedi import Script 

272 >>> source = '''\ 

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

274 ... "Document for function f." 

275 ... ''' 

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

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

278 >>> print(doc) 

279 f(a, b=1) 

280 <BLANKLINE> 

281 Document for function f. 

282 

283 Notice that useful extra information is added to the actual 

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

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

286 

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

288 Document for function f. 

289 

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

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

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

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

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

295 """ 

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

297 return '' 

298 doc = self._get_docstring() 

299 if raw: 

300 return doc 

301 

302 signature_text = self._get_docstring_signature() 

303 if signature_text and doc: 

304 return signature_text + '\n\n' + doc 

305 else: 

306 return signature_text + doc 

307 

308 def _get_docstring(self): 

309 return self._name.py__doc__() 

310 

311 def _get_docstring_signature(self): 

312 return '\n'.join( 

313 signature.to_string() 

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

315 ) 

316 

317 @property 

318 def description(self): 

319 """ 

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

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

322 

323 Example: 

324 

325 >>> from jedi import Script 

326 >>> source = ''' 

327 ... def f(): 

328 ... pass 

329 ... 

330 ... class C: 

331 ... pass 

332 ... 

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

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

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

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

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

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

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

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

341 'def f' 

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

343 'class C' 

344 

345 """ 

346 typ = self.type 

347 tree_name = self._name.tree_name 

348 if typ == 'param': 

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

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

351 if typ == 'function': 

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

353 typ = 'def' 

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

355 

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

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

358 # here. 

359 txt = definition.get_code(include_prefix=False) 

360 # Delete comments: 

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

362 # Delete multi spaces/newlines 

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

364 return txt 

365 

366 @property 

367 def full_name(self): 

368 """ 

369 Dot-separated path of this object. 

370 

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

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

373 object at hand. 

374 

375 Example: 

376 

377 >>> from jedi import Script 

378 >>> source = ''' 

379 ... import os 

380 ... os.path.join''' 

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

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

383 os.path.join 

384 

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

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

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

388 more practical. 

389 """ 

390 if not self._name.is_value_name: 

391 return None 

392 

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

394 if names is None: 

395 return None 

396 

397 names = list(names) 

398 try: 

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

400 except KeyError: 

401 pass 

402 

403 return '.'.join(names) 

404 

405 def is_stub(self): 

406 """ 

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

408 """ 

409 if not self._name.is_value_name: 

410 return False 

411 

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

413 

414 def is_side_effect(self): 

415 """ 

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

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

418 """ 

419 tree_name = self._name.tree_name 

420 if tree_name is None: 

421 return False 

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

423 

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

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

426 only_stubs=False, prefer_stubs=False): 

427 

428 """ 

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

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

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

432 

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

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

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

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

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

438 :rtype: list of :class:`Name` 

439 """ 

440 if not self._name.is_value_name: 

441 return [] 

442 

443 names = self._name.goto() 

444 if follow_imports: 

445 names = filter_follow_imports(names, follow_builtin_imports) 

446 names = convert_names( 

447 names, 

448 only_stubs=only_stubs, 

449 prefer_stubs=prefer_stubs, 

450 ) 

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

452 for n in names] 

453 

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

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

456 """ 

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

458 the current name has. 

459 

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

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

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

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

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

465 it's just very, very slow. 

466 

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

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

469 inference call. 

470 :rtype: list of :class:`Name` 

471 """ 

472 assert not (only_stubs and prefer_stubs) 

473 

474 if not self._name.is_value_name: 

475 return [] 

476 

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

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

479 # results of Python objects instead of stubs. 

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

481 values = convert_values( 

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

483 only_stubs=only_stubs, 

484 prefer_stubs=prefer_stubs, 

485 ) 

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

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

488 for n in resulting_names] 

489 

490 def parent(self): 

491 """ 

492 Returns the parent scope of this identifier. 

493 

494 :rtype: Name 

495 """ 

496 if not self._name.is_value_name: 

497 return None 

498 

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

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

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

502 # The reason for this is the following: 

503 # - class: Nested classes parent_context is always the 

504 # parent_context of the most outer one. 

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

506 # parent_context. 

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

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

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

510 parent = cls_or_func_node.search_ancestor('funcdef', 'classdef', 'file_input') 

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

512 else: 

513 context = self._name.parent_context 

514 

515 if context is None: 

516 return None 

517 while context.name is None: 

518 # Happens for comprehension contexts 

519 context = context.parent_context 

520 

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

522 

523 def __repr__(self): 

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

525 self.__class__.__name__, 

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

527 self.full_name or self.name, 

528 self.description, 

529 ) 

530 

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

532 """ 

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

534 

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

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

537 

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

539 builtin. 

540 """ 

541 if not self._name.is_value_name: 

542 return '' 

543 

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

545 if lines is None: 

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

547 return '' 

548 

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

550 start_index = max(index - before, 0) 

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

552 

553 def _get_signatures(self, for_docstring=False): 

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

555 return [] 

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

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

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

559 return [] 

560 

561 if isinstance(self._name, MixedName): 

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

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

564 # not necessary. 

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

566 

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

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

569 

570 def get_signatures(self): 

571 """ 

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

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

574 

575 :rtype: list of :class:`BaseSignature` 

576 """ 

577 return [ 

578 BaseSignature(self._inference_state, s) 

579 for s in self._get_signatures() 

580 ] 

581 

582 def execute(self): 

583 """ 

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

585 executed objects. 

586 

587 :rtype: list of :class:`Name` 

588 """ 

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

590 

591 def get_type_hint(self): 

592 """ 

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

594 

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

596 is finding executions for those functions to return something like 

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

598 

599 :rtype: str 

600 """ 

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

602 

603 

604class Completion(BaseName): 

605 """ 

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

607 provide additional information about a completion. 

608 """ 

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

610 is_fuzzy, cached_name=None): 

611 super().__init__(inference_state, name) 

612 

613 self._like_name_length = like_name_length 

614 self._stack = stack 

615 self._is_fuzzy = is_fuzzy 

616 self._cached_name = cached_name 

617 

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

619 # duplicate items in the completion) 

620 self._same_name_completions = [] 

621 

622 def _complete(self, like_name): 

623 append = '' 

624 if settings.add_bracket_after_function \ 

625 and self.type == 'function': 

626 append = '(' 

627 

628 name = self._name.get_public_name() 

629 if like_name: 

630 name = name[self._like_name_length:] 

631 return name + append 

632 

633 @property 

634 def complete(self): 

635 """ 

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

637 completions are used. 

638 

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

640 

641 isinstan# <-- Cursor is here 

642 

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

644 on your ``settings.py``. 

645 

646 Assuming the following function definition:: 

647 

648 def foo(param=0): 

649 pass 

650 

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

652 would be ``am=``. 

653 """ 

654 if self._is_fuzzy: 

655 return None 

656 return self._complete(True) 

657 

658 @property 

659 def name_with_symbols(self): 

660 """ 

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

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

663 

664 def foo(param=0): 

665 pass 

666 

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

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

669 

670 """ 

671 return self._complete(False) 

672 

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

674 """ 

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

676 """ 

677 if self._like_name_length >= 3: 

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

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

680 fast = False 

681 

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

683 

684 def _get_docstring(self): 

685 if self._cached_name is not None: 

686 return completion_cache.get_docstring( 

687 self._cached_name, 

688 self._name.get_public_name(), 

689 lambda: self._get_cache() 

690 ) 

691 return super()._get_docstring() 

692 

693 def _get_docstring_signature(self): 

694 if self._cached_name is not None: 

695 return completion_cache.get_docstring_signature( 

696 self._cached_name, 

697 self._name.get_public_name(), 

698 lambda: self._get_cache() 

699 ) 

700 return super()._get_docstring_signature() 

701 

702 def _get_cache(self): 

703 return ( 

704 super().type, 

705 super()._get_docstring_signature(), 

706 super()._get_docstring(), 

707 ) 

708 

709 @property 

710 def type(self): 

711 """ 

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

713 """ 

714 # Purely a speed optimization. 

715 if self._cached_name is not None: 

716 return completion_cache.get_type( 

717 self._cached_name, 

718 self._name.get_public_name(), 

719 lambda: self._get_cache() 

720 ) 

721 

722 return super().type 

723 

724 def get_completion_prefix_length(self): 

725 """ 

726 Returns the length of the prefix being completed. 

727 For example, completing ``isinstance``:: 

728 

729 isinstan# <-- Cursor is here 

730 

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

732 

733 Assuming the following function definition:: 

734 

735 def foo(param=0): 

736 pass 

737 

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

739 """ 

740 return self._like_name_length 

741 

742 def __repr__(self): 

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

744 

745 

746class Name(BaseName): 

747 """ 

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

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

750 """ 

751 def __init__(self, inference_state, definition): 

752 super().__init__(inference_state, definition) 

753 

754 @memoize_method 

755 def defined_names(self): 

756 """ 

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

758 

759 :rtype: list of :class:`Name` 

760 """ 

761 defs = self._name.infer() 

762 return sorted( 

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

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

765 ) 

766 

767 def is_definition(self): 

768 """ 

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

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

771 """ 

772 if self._name.tree_name is None: 

773 return True 

774 else: 

775 return self._name.tree_name.is_definition() 

776 

777 def __eq__(self, other): 

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

779 and self.module_path == other.module_path \ 

780 and self.name == other.name \ 

781 and self._inference_state == other._inference_state 

782 

783 def __ne__(self, other): 

784 return not self.__eq__(other) 

785 

786 def __hash__(self): 

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

788 

789 

790class BaseSignature(Name): 

791 """ 

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

793 calls. 

794 """ 

795 def __init__(self, inference_state, signature): 

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

797 self._signature = signature 

798 

799 @property 

800 def params(self): 

801 """ 

802 Returns definitions for all parameters that a signature defines. 

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

804 

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

806 """ 

807 return [ParamName(self._inference_state, n) 

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

809 

810 def to_string(self): 

811 """ 

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

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

814 

815 :rtype: str 

816 """ 

817 return self._signature.to_string() 

818 

819 

820class Signature(BaseSignature): 

821 """ 

822 A full signature object is the return value of 

823 :meth:`.Script.get_signatures`. 

824 """ 

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

826 super().__init__(inference_state, signature) 

827 self._call_details = call_details 

828 self._signature = signature 

829 

830 @property 

831 def index(self): 

832 """ 

833 Returns the param index of the current cursor position. 

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

835 

836 :rtype: int 

837 """ 

838 return self._call_details.calculate_index( 

839 self._signature.get_param_names(resolve_stars=True) 

840 ) 

841 

842 @property 

843 def bracket_start(self): 

844 """ 

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

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

847 

848 :rtype: int, int 

849 """ 

850 return self._call_details.bracket_leaf.start_pos 

851 

852 def __repr__(self): 

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

854 type(self).__name__, 

855 self.index, 

856 self._signature.to_string(), 

857 ) 

858 

859 

860class ParamName(Name): 

861 def infer_default(self): 

862 """ 

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

864 

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

866 """ 

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

868 

869 def infer_annotation(self, **kwargs): 

870 """ 

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

872 executed and classes are returned instead of instances. 

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

874 """ 

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

876 

877 def to_string(self): 

878 """ 

879 Returns a simple representation of a param, like 

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

881 

882 :rtype: str 

883 """ 

884 return self._name.to_string() 

885 

886 @property 

887 def kind(self): 

888 """ 

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

890 

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

892 """ 

893 return self._name.get_kind()