__init__.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. """
  2. The API basically only provides one class. You can create a :class:`Script` and
  3. use its methods.
  4. Additionally you can add a debug function with :func:`set_debug_function`.
  5. Alternatively, if you don't need a custom function and are happy with printing
  6. debug messages to stdout, simply call :func:`set_debug_function` without
  7. arguments.
  8. """
  9. import sys
  10. from pathlib import Path
  11. import parso
  12. from parso.python import tree
  13. from jedi.parser_utils import get_executable_nodes
  14. from jedi import debug
  15. from jedi import settings
  16. from jedi import cache
  17. from jedi.file_io import KnownContentFileIO
  18. from jedi.api import classes
  19. from jedi.api import interpreter
  20. from jedi.api import helpers
  21. from jedi.api.helpers import validate_line_column
  22. from jedi.api.completion import Completion, search_in_module
  23. from jedi.api.keywords import KeywordName
  24. from jedi.api.environment import InterpreterEnvironment
  25. from jedi.api.project import get_default_project, Project
  26. from jedi.api.errors import parso_to_jedi_errors
  27. from jedi.api import refactoring
  28. from jedi.api.refactoring.extract import extract_function, extract_variable
  29. from jedi.inference import InferenceState
  30. from jedi.inference import imports
  31. from jedi.inference.references import find_references
  32. from jedi.inference.arguments import try_iter_content
  33. from jedi.inference.helpers import infer_call_of_leaf
  34. from jedi.inference.sys_path import transform_path_to_dotted
  35. from jedi.inference.syntax_tree import tree_name_to_values
  36. from jedi.inference.value import ModuleValue
  37. from jedi.inference.base_value import ValueSet
  38. from jedi.inference.value.iterable import unpack_tuple_to_dict
  39. from jedi.inference.gradual.conversion import convert_names, convert_values
  40. from jedi.inference.gradual.utils import load_proper_stub_module
  41. from jedi.inference.utils import to_list
  42. # Jedi uses lots and lots of recursion. By setting this a little bit higher, we
  43. # can remove some "maximum recursion depth" errors.
  44. sys.setrecursionlimit(3000)
  45. class Script:
  46. """
  47. A Script is the base for completions, goto or whatever you want to do with
  48. Jedi. The counter part of this class is :class:`Interpreter`, which works
  49. with actual dictionaries and can work with a REPL. This class
  50. should be used when a user edits code in an editor.
  51. You can either use the ``code`` parameter or ``path`` to read a file.
  52. Usually you're going to want to use both of them (in an editor).
  53. The Script's ``sys.path`` is very customizable:
  54. - If `project` is provided with a ``sys_path``, that is going to be used.
  55. - If `environment` is provided, its ``sys.path`` will be used
  56. (see :func:`Environment.get_sys_path <jedi.api.environment.Environment.get_sys_path>`);
  57. - Otherwise ``sys.path`` will match that of the default environment of
  58. Jedi, which typically matches the sys path that was used at the time
  59. when Jedi was imported.
  60. Most methods have a ``line`` and a ``column`` parameter. Lines in Jedi are
  61. always 1-based and columns are always zero based. To avoid repetition they
  62. are not always documented. You can omit both line and column. Jedi will
  63. then just do whatever action you are calling at the end of the file. If you
  64. provide only the line, just will complete at the end of that line.
  65. .. warning:: By default :attr:`jedi.settings.fast_parser` is enabled, which means
  66. that parso reuses modules (i.e. they are not immutable). With this setting
  67. Jedi is **not thread safe** and it is also not safe to use multiple
  68. :class:`.Script` instances and its definitions at the same time.
  69. If you are a normal plugin developer this should not be an issue. It is
  70. an issue for people that do more complex stuff with Jedi.
  71. This is purely a performance optimization and works pretty well for all
  72. typical usages, however consider to turn the setting off if it causes
  73. you problems. See also
  74. `this discussion <https://github.com/davidhalter/jedi/issues/1240>`_.
  75. :param code: The source code of the current file, separated by newlines.
  76. :type code: str
  77. :param path: The path of the file in the file system, or ``''`` if
  78. it hasn't been saved yet.
  79. :type path: str or pathlib.Path or None
  80. :param Environment environment: Provide a predefined :ref:`Environment <environments>`
  81. to work with a specific Python version or virtualenv.
  82. :param Project project: Provide a :class:`.Project` to make sure finding
  83. references works well, because the right folder is searched. There are
  84. also ways to modify the sys path and other things.
  85. """
  86. def __init__(self, code=None, *, path=None, environment=None, project=None):
  87. self._orig_path = path
  88. if isinstance(path, str):
  89. path = Path(path)
  90. self.path = path.absolute() if path else None
  91. if code is None:
  92. if path is None:
  93. raise ValueError("Must provide at least one of code or path")
  94. # TODO add a better warning than the traceback!
  95. with open(path, 'rb') as f:
  96. code = f.read()
  97. if project is None:
  98. # Load the Python grammar of the current interpreter.
  99. project = get_default_project(None if self.path is None else self.path.parent)
  100. self._inference_state = InferenceState(
  101. project, environment=environment, script_path=self.path
  102. )
  103. debug.speed('init')
  104. self._module_node, code = self._inference_state.parse_and_get_code(
  105. code=code,
  106. path=self.path,
  107. use_latest_grammar=path and path.suffix == '.pyi',
  108. cache=False, # No disk cache, because the current script often changes.
  109. diff_cache=settings.fast_parser,
  110. cache_path=settings.cache_directory,
  111. )
  112. debug.speed('parsed')
  113. self._code_lines = parso.split_lines(code, keepends=True)
  114. self._code = code
  115. cache.clear_time_caches()
  116. debug.reset_time()
  117. # Cache the module, this is mostly useful for testing, since this shouldn't
  118. # be called multiple times.
  119. @cache.memoize_method
  120. def _get_module(self):
  121. names = None
  122. is_package = False
  123. if self.path is not None:
  124. import_names, is_p = transform_path_to_dotted(
  125. self._inference_state.get_sys_path(add_parent_paths=False),
  126. self.path
  127. )
  128. if import_names is not None:
  129. names = import_names
  130. is_package = is_p
  131. if self.path is None:
  132. file_io = None
  133. else:
  134. file_io = KnownContentFileIO(self.path, self._code)
  135. if self.path is not None and self.path.suffix == '.pyi':
  136. # We are in a stub file. Try to load the stub properly.
  137. stub_module = load_proper_stub_module(
  138. self._inference_state,
  139. self._inference_state.latest_grammar,
  140. file_io,
  141. names,
  142. self._module_node
  143. )
  144. if stub_module is not None:
  145. return stub_module
  146. if names is None:
  147. names = ('__main__',)
  148. module = ModuleValue(
  149. self._inference_state, self._module_node,
  150. file_io=file_io,
  151. string_names=names,
  152. code_lines=self._code_lines,
  153. is_package=is_package,
  154. )
  155. if names[0] not in ('builtins', 'typing'):
  156. # These modules are essential for Jedi, so don't overwrite them.
  157. self._inference_state.module_cache.add(names, ValueSet([module]))
  158. return module
  159. def _get_module_context(self):
  160. return self._get_module().as_context()
  161. def __repr__(self):
  162. return '<%s: %s %r>' % (
  163. self.__class__.__name__,
  164. repr(self._orig_path),
  165. self._inference_state.environment,
  166. )
  167. @validate_line_column
  168. def complete(self, line=None, column=None, *, fuzzy=False):
  169. """
  170. Completes objects under the cursor.
  171. Those objects contain information about the completions, more than just
  172. names.
  173. :param fuzzy: Default False. Will return fuzzy completions, which means
  174. that e.g. ``ooa`` will match ``foobar``.
  175. :return: Completion objects, sorted by name. Normal names appear
  176. before "private" names that start with ``_`` and those appear
  177. before magic methods and name mangled names that start with ``__``.
  178. :rtype: list of :class:`.Completion`
  179. """
  180. self._inference_state.reset_recursion_limitations()
  181. with debug.increase_indent_cm('complete'):
  182. completion = Completion(
  183. self._inference_state, self._get_module_context(), self._code_lines,
  184. (line, column), self.get_signatures, fuzzy=fuzzy,
  185. )
  186. return completion.complete()
  187. @validate_line_column
  188. def infer(self, line=None, column=None, *, only_stubs=False, prefer_stubs=False):
  189. """
  190. Return the definitions of under the cursor. It is basically a wrapper
  191. around Jedi's type inference.
  192. This method follows complicated paths and returns the end, not the
  193. first definition. The big difference between :meth:`goto` and
  194. :meth:`infer` is that :meth:`goto` doesn't
  195. follow imports and statements. Multiple objects may be returned,
  196. because depending on an option you can have two different versions of a
  197. function.
  198. :param only_stubs: Only return stubs for this method.
  199. :param prefer_stubs: Prefer stubs to Python objects for this method.
  200. :rtype: list of :class:`.Name`
  201. """
  202. self._inference_state.reset_recursion_limitations()
  203. pos = line, column
  204. leaf = self._module_node.get_name_of_position(pos)
  205. if leaf is None:
  206. leaf = self._module_node.get_leaf_for_position(pos)
  207. if leaf is None or leaf.type == 'string':
  208. return []
  209. if leaf.end_pos == (line, column) and leaf.type == 'operator':
  210. next_ = leaf.get_next_leaf()
  211. if next_.start_pos == leaf.end_pos \
  212. and next_.type in ('number', 'string', 'keyword'):
  213. leaf = next_
  214. context = self._get_module_context().create_context(leaf)
  215. values = helpers.infer(self._inference_state, context, leaf)
  216. values = convert_values(
  217. values,
  218. only_stubs=only_stubs,
  219. prefer_stubs=prefer_stubs,
  220. )
  221. defs = [classes.Name(self._inference_state, c.name) for c in values]
  222. # The additional set here allows the definitions to become unique in an
  223. # API sense. In the internals we want to separate more things than in
  224. # the API.
  225. return helpers.sorted_definitions(set(defs))
  226. @validate_line_column
  227. def goto(self, line=None, column=None, *, follow_imports=False, follow_builtin_imports=False,
  228. only_stubs=False, prefer_stubs=False):
  229. """
  230. Goes to the name that defined the object under the cursor. Optionally
  231. you can follow imports.
  232. Multiple objects may be returned, depending on an if you can have two
  233. different versions of a function.
  234. :param follow_imports: The method will follow imports.
  235. :param follow_builtin_imports: If ``follow_imports`` is True will try
  236. to look up names in builtins (i.e. compiled or extension modules).
  237. :param only_stubs: Only return stubs for this method.
  238. :param prefer_stubs: Prefer stubs to Python objects for this method.
  239. :rtype: list of :class:`.Name`
  240. """
  241. self._inference_state.reset_recursion_limitations()
  242. tree_name = self._module_node.get_name_of_position((line, column))
  243. if tree_name is None:
  244. # Without a name we really just want to jump to the result e.g.
  245. # executed by `foo()`, if we the cursor is after `)`.
  246. return self.infer(line, column, only_stubs=only_stubs, prefer_stubs=prefer_stubs)
  247. name = self._get_module_context().create_name(tree_name)
  248. # Make it possible to goto the super class function/attribute
  249. # definitions, when they are overwritten.
  250. names = []
  251. if name.tree_name.is_definition() and name.parent_context.is_class():
  252. class_node = name.parent_context.tree_node
  253. class_value = self._get_module_context().create_value(class_node)
  254. mro = class_value.py__mro__()
  255. next(mro) # Ignore the first entry, because it's the class itself.
  256. for cls in mro:
  257. names = cls.goto(tree_name.value)
  258. if names:
  259. break
  260. if not names:
  261. names = list(name.goto())
  262. if follow_imports:
  263. names = helpers.filter_follow_imports(names, follow_builtin_imports)
  264. names = convert_names(
  265. names,
  266. only_stubs=only_stubs,
  267. prefer_stubs=prefer_stubs,
  268. )
  269. defs = [classes.Name(self._inference_state, d) for d in set(names)]
  270. # Avoid duplicates
  271. return list(set(helpers.sorted_definitions(defs)))
  272. def search(self, string, *, all_scopes=False):
  273. """
  274. Searches a name in the current file. For a description of how the
  275. search string should look like, please have a look at
  276. :meth:`.Project.search`.
  277. :param bool all_scopes: Default False; searches not only for
  278. definitions on the top level of a module level, but also in
  279. functions and classes.
  280. :yields: :class:`.Name`
  281. """
  282. return self._search_func(string, all_scopes=all_scopes)
  283. @to_list
  284. def _search_func(self, string, all_scopes=False, complete=False, fuzzy=False):
  285. names = self._names(all_scopes=all_scopes)
  286. wanted_type, wanted_names = helpers.split_search_string(string)
  287. return search_in_module(
  288. self._inference_state,
  289. self._get_module_context(),
  290. names=names,
  291. wanted_type=wanted_type,
  292. wanted_names=wanted_names,
  293. complete=complete,
  294. fuzzy=fuzzy,
  295. )
  296. def complete_search(self, string, **kwargs):
  297. """
  298. Like :meth:`.Script.search`, but completes that string. If you want to
  299. have all possible definitions in a file you can also provide an empty
  300. string.
  301. :param bool all_scopes: Default False; searches not only for
  302. definitions on the top level of a module level, but also in
  303. functions and classes.
  304. :param fuzzy: Default False. Will return fuzzy completions, which means
  305. that e.g. ``ooa`` will match ``foobar``.
  306. :yields: :class:`.Completion`
  307. """
  308. return self._search_func(string, complete=True, **kwargs)
  309. @validate_line_column
  310. def help(self, line=None, column=None):
  311. """
  312. Used to display a help window to users. Uses :meth:`.Script.goto` and
  313. returns additional definitions for keywords and operators.
  314. Typically you will want to display :meth:`.BaseName.docstring` to the
  315. user for all the returned definitions.
  316. The additional definitions are ``Name(...).type == 'keyword'``.
  317. These definitions do not have a lot of value apart from their docstring
  318. attribute, which contains the output of Python's :func:`help` function.
  319. :rtype: list of :class:`.Name`
  320. """
  321. self._inference_state.reset_recursion_limitations()
  322. definitions = self.goto(line, column, follow_imports=True)
  323. if definitions:
  324. return definitions
  325. leaf = self._module_node.get_leaf_for_position((line, column))
  326. if leaf is not None and leaf.end_pos == (line, column) and leaf.type == 'newline':
  327. next_ = leaf.get_next_leaf()
  328. if next_ is not None and next_.start_pos == leaf.end_pos:
  329. leaf = next_
  330. if leaf is not None and leaf.type in ('keyword', 'operator', 'error_leaf'):
  331. def need_pydoc():
  332. if leaf.value in ('(', ')', '[', ']'):
  333. if leaf.parent.type == 'trailer':
  334. return False
  335. if leaf.parent.type == 'atom':
  336. return False
  337. grammar = self._inference_state.grammar
  338. # This parso stuff is not public, but since I control it, this
  339. # is fine :-) ~dave
  340. reserved = grammar._pgen_grammar.reserved_syntax_strings.keys()
  341. return leaf.value in reserved
  342. if need_pydoc():
  343. name = KeywordName(self._inference_state, leaf.value)
  344. return [classes.Name(self._inference_state, name)]
  345. return []
  346. @validate_line_column
  347. def get_references(self, line=None, column=None, **kwargs):
  348. """
  349. Lists all references of a variable in a project. Since this can be
  350. quite hard to do for Jedi, if it is too complicated, Jedi will stop
  351. searching.
  352. :param include_builtins: Default ``True``. If ``False``, checks if a definition
  353. is a builtin (e.g. ``sys``) and in that case does not return it.
  354. :param scope: Default ``'project'``. If ``'file'``, include references in
  355. the current module only.
  356. :rtype: list of :class:`.Name`
  357. """
  358. self._inference_state.reset_recursion_limitations()
  359. def _references(include_builtins=True, scope='project'):
  360. if scope not in ('project', 'file'):
  361. raise ValueError('Only the scopes "file" and "project" are allowed')
  362. tree_name = self._module_node.get_name_of_position((line, column))
  363. if tree_name is None:
  364. # Must be syntax
  365. return []
  366. names = find_references(self._get_module_context(), tree_name, scope == 'file')
  367. definitions = [classes.Name(self._inference_state, n) for n in names]
  368. if not include_builtins or scope == 'file':
  369. definitions = [d for d in definitions if not d.in_builtin_module()]
  370. return helpers.sorted_definitions(definitions)
  371. return _references(**kwargs)
  372. @validate_line_column
  373. def get_signatures(self, line=None, column=None):
  374. """
  375. Return the function object of the call under the cursor.
  376. E.g. if the cursor is here::
  377. abs(# <-- cursor is here
  378. This would return the ``abs`` function. On the other hand::
  379. abs()# <-- cursor is here
  380. This would return an empty list..
  381. :rtype: list of :class:`.Signature`
  382. """
  383. self._inference_state.reset_recursion_limitations()
  384. pos = line, column
  385. call_details = helpers.get_signature_details(self._module_node, pos)
  386. if call_details is None:
  387. return []
  388. context = self._get_module_context().create_context(call_details.bracket_leaf)
  389. definitions = helpers.cache_signatures(
  390. self._inference_state,
  391. context,
  392. call_details.bracket_leaf,
  393. self._code_lines,
  394. pos
  395. )
  396. debug.speed('func_call followed')
  397. # TODO here we use stubs instead of the actual values. We should use
  398. # the signatures from stubs, but the actual values, probably?!
  399. return [classes.Signature(self._inference_state, signature, call_details)
  400. for signature in definitions.get_signatures()]
  401. @validate_line_column
  402. def get_context(self, line=None, column=None):
  403. """
  404. Returns the scope context under the cursor. This basically means the
  405. function, class or module where the cursor is at.
  406. :rtype: :class:`.Name`
  407. """
  408. pos = (line, column)
  409. leaf = self._module_node.get_leaf_for_position(pos, include_prefixes=True)
  410. if leaf.start_pos > pos or leaf.type == 'endmarker':
  411. previous_leaf = leaf.get_previous_leaf()
  412. if previous_leaf is not None:
  413. leaf = previous_leaf
  414. module_context = self._get_module_context()
  415. n = tree.search_ancestor(leaf, 'funcdef', 'classdef')
  416. if n is not None and n.start_pos < pos <= n.children[-1].start_pos:
  417. # This is a bit of a special case. The context of a function/class
  418. # name/param/keyword is always it's parent context, not the
  419. # function itself. Catch all the cases here where we are before the
  420. # suite object, but still in the function.
  421. context = module_context.create_value(n).as_context()
  422. else:
  423. context = module_context.create_context(leaf)
  424. while context.name is None:
  425. context = context.parent_context # comprehensions
  426. definition = classes.Name(self._inference_state, context.name)
  427. while definition.type != 'module':
  428. name = definition._name # TODO private access
  429. tree_name = name.tree_name
  430. if tree_name is not None: # Happens with lambdas.
  431. scope = tree_name.get_definition()
  432. if scope.start_pos[1] < column:
  433. break
  434. definition = definition.parent()
  435. return definition
  436. def _analysis(self):
  437. self._inference_state.is_analysis = True
  438. self._inference_state.analysis_modules = [self._module_node]
  439. module = self._get_module_context()
  440. try:
  441. for node in get_executable_nodes(self._module_node):
  442. context = module.create_context(node)
  443. if node.type in ('funcdef', 'classdef'):
  444. # Resolve the decorators.
  445. tree_name_to_values(self._inference_state, context, node.children[1])
  446. elif isinstance(node, tree.Import):
  447. import_names = set(node.get_defined_names())
  448. if node.is_nested():
  449. import_names |= set(path[-1] for path in node.get_paths())
  450. for n in import_names:
  451. imports.infer_import(context, n)
  452. elif node.type == 'expr_stmt':
  453. types = context.infer_node(node)
  454. for testlist in node.children[:-1:2]:
  455. # Iterate tuples.
  456. unpack_tuple_to_dict(context, types, testlist)
  457. else:
  458. if node.type == 'name':
  459. defs = self._inference_state.infer(context, node)
  460. else:
  461. defs = infer_call_of_leaf(context, node)
  462. try_iter_content(defs)
  463. self._inference_state.reset_recursion_limitations()
  464. ana = [a for a in self._inference_state.analysis if self.path == a.path]
  465. return sorted(set(ana), key=lambda x: x.line)
  466. finally:
  467. self._inference_state.is_analysis = False
  468. def get_names(self, **kwargs):
  469. """
  470. Returns names defined in the current file.
  471. :param all_scopes: If True lists the names of all scopes instead of
  472. only the module namespace.
  473. :param definitions: If True lists the names that have been defined by a
  474. class, function or a statement (``a = b`` returns ``a``).
  475. :param references: If True lists all the names that are not listed by
  476. ``definitions=True``. E.g. ``a = b`` returns ``b``.
  477. :rtype: list of :class:`.Name`
  478. """
  479. names = self._names(**kwargs)
  480. return [classes.Name(self._inference_state, n) for n in names]
  481. def get_syntax_errors(self):
  482. """
  483. Lists all syntax errors in the current file.
  484. :rtype: list of :class:`.SyntaxError`
  485. """
  486. return parso_to_jedi_errors(self._inference_state.grammar, self._module_node)
  487. def _names(self, all_scopes=False, definitions=True, references=False):
  488. self._inference_state.reset_recursion_limitations()
  489. # Set line/column to a random position, because they don't matter.
  490. module_context = self._get_module_context()
  491. defs = [
  492. module_context.create_name(name)
  493. for name in helpers.get_module_names(
  494. self._module_node,
  495. all_scopes=all_scopes,
  496. definitions=definitions,
  497. references=references,
  498. )
  499. ]
  500. return sorted(defs, key=lambda x: x.start_pos)
  501. def rename(self, line=None, column=None, *, new_name):
  502. """
  503. Renames all references of the variable under the cursor.
  504. :param new_name: The variable under the cursor will be renamed to this
  505. string.
  506. :raises: :exc:`.RefactoringError`
  507. :rtype: :class:`.Refactoring`
  508. """
  509. definitions = self.get_references(line, column, include_builtins=False)
  510. return refactoring.rename(self._inference_state, definitions, new_name)
  511. @validate_line_column
  512. def extract_variable(self, line, column, *, new_name, until_line=None, until_column=None):
  513. """
  514. Moves an expression to a new statement.
  515. For example if you have the cursor on ``foo`` and provide a
  516. ``new_name`` called ``bar``::
  517. foo = 3.1
  518. x = int(foo + 1)
  519. the code above will become::
  520. foo = 3.1
  521. bar = foo + 1
  522. x = int(bar)
  523. :param new_name: The expression under the cursor will be renamed to
  524. this string.
  525. :param int until_line: The the selection range ends at this line, when
  526. omitted, Jedi will be clever and try to define the range itself.
  527. :param int until_column: The the selection range ends at this column, when
  528. omitted, Jedi will be clever and try to define the range itself.
  529. :raises: :exc:`.RefactoringError`
  530. :rtype: :class:`.Refactoring`
  531. """
  532. if until_line is None and until_column is None:
  533. until_pos = None
  534. else:
  535. if until_line is None:
  536. until_line = line
  537. if until_column is None:
  538. until_column = len(self._code_lines[until_line - 1])
  539. until_pos = until_line, until_column
  540. return extract_variable(
  541. self._inference_state, self.path, self._module_node,
  542. new_name, (line, column), until_pos
  543. )
  544. @validate_line_column
  545. def extract_function(self, line, column, *, new_name, until_line=None, until_column=None):
  546. """
  547. Moves an expression to a new function.
  548. For example if you have the cursor on ``foo`` and provide a
  549. ``new_name`` called ``bar``::
  550. global_var = 3
  551. def x():
  552. foo = 3.1
  553. x = int(foo + 1 + global_var)
  554. the code above will become::
  555. global_var = 3
  556. def bar(foo):
  557. return int(foo + 1 + global_var)
  558. def x():
  559. foo = 3.1
  560. x = bar(foo)
  561. :param new_name: The expression under the cursor will be replaced with
  562. a function with this name.
  563. :param int until_line: The the selection range ends at this line, when
  564. omitted, Jedi will be clever and try to define the range itself.
  565. :param int until_column: The the selection range ends at this column, when
  566. omitted, Jedi will be clever and try to define the range itself.
  567. :raises: :exc:`.RefactoringError`
  568. :rtype: :class:`.Refactoring`
  569. """
  570. if until_line is None and until_column is None:
  571. until_pos = None
  572. else:
  573. if until_line is None:
  574. until_line = line
  575. if until_column is None:
  576. until_column = len(self._code_lines[until_line - 1])
  577. until_pos = until_line, until_column
  578. return extract_function(
  579. self._inference_state, self.path, self._get_module_context(),
  580. new_name, (line, column), until_pos
  581. )
  582. def inline(self, line=None, column=None):
  583. """
  584. Inlines a variable under the cursor. This is basically the opposite of
  585. extracting a variable. For example with the cursor on bar::
  586. foo = 3.1
  587. bar = foo + 1
  588. x = int(bar)
  589. the code above will become::
  590. foo = 3.1
  591. x = int(foo + 1)
  592. :raises: :exc:`.RefactoringError`
  593. :rtype: :class:`.Refactoring`
  594. """
  595. names = [d._name for d in self.get_references(line, column, include_builtins=True)]
  596. return refactoring.inline(self._inference_state, names)
  597. class Interpreter(Script):
  598. """
  599. Jedi's API for Python REPLs.
  600. Implements all of the methods that are present in :class:`.Script` as well.
  601. In addition to completions that normal REPL completion does like
  602. ``str.upper``, Jedi also supports code completion based on static code
  603. analysis. For example Jedi will complete ``str().upper``.
  604. >>> from os.path import join
  605. >>> namespace = locals()
  606. >>> script = Interpreter('join("").up', [namespace])
  607. >>> print(script.complete()[0].name)
  608. upper
  609. All keyword arguments are same as the arguments for :class:`.Script`.
  610. :param str code: Code to parse.
  611. :type namespaces: typing.List[dict]
  612. :param namespaces: A list of namespace dictionaries such as the one
  613. returned by :func:`globals` and :func:`locals`.
  614. """
  615. def __init__(self, code, namespaces, *, project=None, **kwds):
  616. try:
  617. namespaces = [dict(n) for n in namespaces]
  618. except Exception:
  619. raise TypeError("namespaces must be a non-empty list of dicts.")
  620. environment = kwds.get('environment', None)
  621. if environment is None:
  622. environment = InterpreterEnvironment()
  623. else:
  624. if not isinstance(environment, InterpreterEnvironment):
  625. raise TypeError("The environment needs to be an InterpreterEnvironment subclass.")
  626. if project is None:
  627. project = Project(Path.cwd())
  628. super().__init__(code, environment=environment, project=project, **kwds)
  629. self.namespaces = namespaces
  630. self._inference_state.allow_unsafe_executions = \
  631. settings.allow_unsafe_interpreter_executions
  632. # Dynamic params search is important when we work on functions that are
  633. # called by other pieces of code. However for interpreter completions
  634. # this is not important at all, because the current code is always new
  635. # and will never be called by something.
  636. # Also sometimes this logic goes a bit too far like in
  637. # https://github.com/ipython/ipython/issues/13866, where it takes
  638. # seconds to do a simple completion.
  639. self._inference_state.do_dynamic_params_search = False
  640. @cache.memoize_method
  641. def _get_module_context(self):
  642. if self.path is None:
  643. file_io = None
  644. else:
  645. file_io = KnownContentFileIO(self.path, self._code)
  646. tree_module_value = ModuleValue(
  647. self._inference_state, self._module_node,
  648. file_io=file_io,
  649. string_names=('__main__',),
  650. code_lines=self._code_lines,
  651. )
  652. return interpreter.MixedModuleContext(
  653. tree_module_value,
  654. self.namespaces,
  655. )
  656. def preload_module(*modules):
  657. """
  658. Preloading modules tells Jedi to load a module now, instead of lazy parsing
  659. of modules. This can be useful for IDEs, to control which modules to load
  660. on startup.
  661. :param modules: different module names, list of string.
  662. """
  663. for m in modules:
  664. s = "import %s as x; x." % m
  665. Script(s).complete(1, len(s))
  666. def set_debug_function(func_cb=debug.print_to_stdout, warnings=True,
  667. notices=True, speed=True):
  668. """
  669. Define a callback debug function to get all the debug messages.
  670. If you don't specify any arguments, debug messages will be printed to stdout.
  671. :param func_cb: The callback function for debug messages.
  672. """
  673. debug.debug_function = func_cb
  674. debug.enable_warning = warnings
  675. debug.enable_notice = notices
  676. debug.enable_speed = speed