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

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

317 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, recursion_limit 

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.14/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 @recursion_limit 

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

267 r""" 

268 Return a document string for this completion object. 

269 

270 Example: 

271 

272 >>> from jedi import Script 

273 >>> source = '''\ 

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

275 ... "Document for function f." 

276 ... ''' 

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

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

279 >>> print(doc) 

280 f(a, b=1) 

281 <BLANKLINE> 

282 Document for function f. 

283 

284 Notice that useful extra information is added to the actual 

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

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

287 

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

289 Document for function f. 

290 

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

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

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

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

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

296 """ 

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

298 return '' 

299 doc = self._get_docstring() 

300 if raw: 

301 return doc 

302 

303 signature_text = self._get_docstring_signature() 

304 if signature_text and doc: 

305 return signature_text + '\n\n' + doc 

306 else: 

307 return signature_text + doc 

308 

309 def _get_docstring(self): 

310 return self._name.py__doc__() 

311 

312 def _get_docstring_signature(self): 

313 return '\n'.join( 

314 signature.to_string() 

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

316 ) 

317 

318 @property 

319 def description(self): 

320 """ 

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

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

323 

324 Example: 

325 

326 >>> from jedi import Script 

327 >>> source = ''' 

328 ... def f(): 

329 ... pass 

330 ... 

331 ... class C: 

332 ... pass 

333 ... 

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

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

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

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

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

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

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

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

342 'def f' 

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

344 'class C' 

345 

346 """ 

347 typ = self.type 

348 tree_name = self._name.tree_name 

349 if typ == 'param': 

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

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

352 if typ == 'function': 

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

354 typ = 'def' 

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

356 

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

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

359 # here. 

360 txt = definition.get_code(include_prefix=False) 

361 # Delete comments: 

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

363 # Delete multi spaces/newlines 

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

365 return txt 

366 

367 @property 

368 def full_name(self): 

369 """ 

370 Dot-separated path of this object. 

371 

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

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

374 object at hand. 

375 

376 Example: 

377 

378 >>> from jedi import Script 

379 >>> source = ''' 

380 ... import os 

381 ... os.path.join''' 

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

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

384 os.path.join 

385 

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

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

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

389 more practical. 

390 """ 

391 if not self._name.is_value_name: 

392 return None 

393 

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

395 if names is None: 

396 return None 

397 

398 names = list(names) 

399 try: 

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

401 except KeyError: 

402 pass 

403 

404 return '.'.join(names) 

405 

406 def is_stub(self): 

407 """ 

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

409 """ 

410 if not self._name.is_value_name: 

411 return False 

412 

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

414 

415 def is_side_effect(self): 

416 """ 

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

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

419 """ 

420 tree_name = self._name.tree_name 

421 if tree_name is None: 

422 return False 

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

424 

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

426 @recursion_limit 

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

428 only_stubs=False, prefer_stubs=False): 

429 

430 """ 

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

434 

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` 

441 """ 

442 if not self._name.is_value_name: 

443 return [] 

444 

445 names = self._name.goto() 

446 if follow_imports: 

447 names = filter_follow_imports(names, follow_builtin_imports) 

448 names = convert_names( 

449 names, 

450 only_stubs=only_stubs, 

451 prefer_stubs=prefer_stubs, 

452 ) 

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

454 for n in names] 

455 

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

457 @recursion_limit 

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 = cls_or_func_node.search_ancestor('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 in ('property', 'param'): 

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 @recursion_limit 

574 def get_signatures(self): 

575 """ 

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

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

578 

579 :rtype: list of :class:`BaseSignature` 

580 """ 

581 return [ 

582 BaseSignature(self._inference_state, s) 

583 for s in self._get_signatures() 

584 ] 

585 

586 @recursion_limit 

587 def execute(self): 

588 """ 

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

590 executed objects. 

591 

592 :rtype: list of :class:`Name` 

593 """ 

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

595 

596 @recursion_limit 

597 def get_type_hint(self): 

598 """ 

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

600 

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

602 is finding executions for those functions to return something like 

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

604 

605 :rtype: str 

606 """ 

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

608 

609 

610class Completion(BaseName): 

611 """ 

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

613 provide additional information about a completion. 

614 """ 

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

616 is_fuzzy, cached_name=None): 

617 super().__init__(inference_state, name) 

618 

619 self._like_name_length = like_name_length 

620 self._stack = stack 

621 self._is_fuzzy = is_fuzzy 

622 self._cached_name = cached_name 

623 

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

625 # duplicate items in the completion) 

626 self._same_name_completions = [] 

627 

628 def _complete(self, like_name): 

629 append = '' 

630 if settings.add_bracket_after_function \ 

631 and self.type == 'function': 

632 append = '(' 

633 

634 name = self._name.get_public_name() 

635 if like_name: 

636 name = name[self._like_name_length:] 

637 return name + append 

638 

639 @property 

640 def complete(self): 

641 """ 

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

643 completions are used. 

644 

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

646 

647 isinstan# <-- Cursor is here 

648 

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

650 on your ``settings.py``. 

651 

652 Assuming the following function definition:: 

653 

654 def foo(param=0): 

655 pass 

656 

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

658 would be ``am=``. 

659 """ 

660 if self._is_fuzzy: 

661 return None 

662 return self._complete(True) 

663 

664 @property 

665 def name_with_symbols(self): 

666 """ 

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

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

669 

670 def foo(param=0): 

671 pass 

672 

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

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

675 

676 """ 

677 return self._complete(False) 

678 

679 @recursion_limit 

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

681 """ 

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

683 """ 

684 if self._like_name_length >= 3: 

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

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

687 fast = False 

688 

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

690 

691 def _get_docstring(self): 

692 if self._cached_name is not None: 

693 return completion_cache.get_docstring( 

694 self._cached_name, 

695 self._name.get_public_name(), 

696 lambda: self._get_cache() 

697 ) 

698 return super()._get_docstring() 

699 

700 def _get_docstring_signature(self): 

701 if self._cached_name is not None: 

702 return completion_cache.get_docstring_signature( 

703 self._cached_name, 

704 self._name.get_public_name(), 

705 lambda: self._get_cache() 

706 ) 

707 return super()._get_docstring_signature() 

708 

709 def _get_cache(self): 

710 return ( 

711 super().type, 

712 super()._get_docstring_signature(), 

713 super()._get_docstring(), 

714 ) 

715 

716 @property 

717 def type(self): 

718 """ 

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

720 """ 

721 # Purely a speed optimization. 

722 if self._cached_name is not None: 

723 return completion_cache.get_type( 

724 self._cached_name, 

725 self._name.get_public_name(), 

726 lambda: self._get_cache() 

727 ) 

728 

729 return super().type 

730 

731 def get_completion_prefix_length(self): 

732 """ 

733 Returns the length of the prefix being completed. 

734 For example, completing ``isinstance``:: 

735 

736 isinstan# <-- Cursor is here 

737 

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

739 

740 Assuming the following function definition:: 

741 

742 def foo(param=0): 

743 pass 

744 

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

746 """ 

747 return self._like_name_length 

748 

749 def __repr__(self): 

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

751 

752 

753class Name(BaseName): 

754 """ 

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

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

757 """ 

758 def __init__(self, inference_state, definition): 

759 super().__init__(inference_state, definition) 

760 

761 @memoize_method 

762 @recursion_limit 

763 def defined_names(self): 

764 """ 

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

766 

767 :rtype: list of :class:`Name` 

768 """ 

769 defs = self._name.infer() 

770 return sorted( 

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

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

773 ) 

774 

775 def is_definition(self): 

776 """ 

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

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

779 """ 

780 if self._name.tree_name is None: 

781 return True 

782 else: 

783 return self._name.tree_name.is_definition() 

784 

785 def __eq__(self, other): 

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

787 and self.module_path == other.module_path \ 

788 and self.name == other.name \ 

789 and self._inference_state == other._inference_state 

790 

791 def __ne__(self, other): 

792 return not self.__eq__(other) 

793 

794 def __hash__(self): 

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

796 

797 

798class BaseSignature(Name): 

799 """ 

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

801 calls. 

802 """ 

803 def __init__(self, inference_state, signature): 

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

805 self._signature = signature 

806 

807 @property 

808 @recursion_limit 

809 def params(self): 

810 """ 

811 Returns definitions for all parameters that a signature defines. 

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

813 

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

815 """ 

816 return [ParamName(self._inference_state, n) 

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

818 

819 @recursion_limit 

820 def to_string(self): 

821 """ 

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

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

824 

825 :rtype: str 

826 """ 

827 return self._signature.to_string() 

828 

829 

830class Signature(BaseSignature): 

831 """ 

832 A full signature object is the return value of 

833 :meth:`.Script.get_signatures`. 

834 """ 

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

836 super().__init__(inference_state, signature) 

837 self._call_details = call_details 

838 self._signature = signature 

839 

840 @property 

841 def index(self): 

842 """ 

843 Returns the param index of the current cursor position. 

844 Returns None if the index cannot be found in the current call. 

845 

846 :rtype: int 

847 """ 

848 return self._call_details.calculate_index( 

849 self._signature.get_param_names(resolve_stars=True) 

850 ) 

851 

852 @property 

853 def bracket_start(self): 

854 """ 

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

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

857 

858 :rtype: int, int 

859 """ 

860 return self._call_details.bracket_leaf.start_pos 

861 

862 def __repr__(self): 

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

864 type(self).__name__, 

865 self.index, 

866 self._signature.to_string(), 

867 ) 

868 

869 

870class ParamName(Name): 

871 @recursion_limit 

872 def infer_default(self): 

873 """ 

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

875 

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

877 """ 

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

879 

880 @recursion_limit 

881 def infer_annotation(self, **kwargs): 

882 """ 

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

884 executed and classes are returned instead of instances. 

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

886 """ 

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

888 

889 @recursion_limit 

890 def to_string(self): 

891 """ 

892 Returns a simple representation of a param, like 

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

894 

895 :rtype: str 

896 """ 

897 return self._name.to_string() 

898 

899 @property 

900 def kind(self): 

901 """ 

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

903 

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

905 """ 

906 return self._name.get_kind()