API Overview

Note

This documentation is mostly for Plugin developers, who want to improve their editors/IDE with Jedi.

The API consists of a few different parts:

The methods that you are most likely going to use to work with Jedi are the following ones:

Script.complete Completes objects under the cursor.
Script.goto Goes to the name that defined the object under the cursor.
Script.infer Return the definitions of under the cursor.
Script.help Used to display a help window to users.
Script.get_signatures Return the function object of the call under the cursor.
Script.get_references Lists all references of a variable in a project.
Script.get_context Returns the scope context under the cursor.
Script.get_names Returns names defined in the current file.
Script.get_syntax_errors Lists all syntax errors in the current file.
Script.rename Renames all references of the variable under the cursor.
Script.inline Inlines a variable under the cursor.
Script.extract_variable Moves an expression to a new statemenet.
Script.extract_function Moves an expression to a new function.
Script.search Searches a name in the current file.
Script.complete_search Like Script.search(), but completes that string.
Project.search Searches a name in the whole project.
Project.complete_search Like Script.search(), but completes that string.

Script

class jedi.Script(code=None, line=None, column=None, path=None, encoding=None, sys_path=None, environment=None, project=None, source=None)[source]

A Script is the base for completions, goto or whatever you want to do with Jedi. The counter part of this class is Interpreter, which works with actual dictionaries and can work with a REPL. This class should be used when a user edits code in an editor.

You can either use the code parameter or path to read a file. Usually you’re going to want to use both of them (in an editor).

The Script’s sys.path is very customizable:

  • If project is provided with a sys_path, that is going to be used.
  • If environment is provided, its sys.path will be used (see Environment.get_sys_path);
  • Otherwise sys.path will match that of the default environment of Jedi, which typically matches the sys path that was used at the time when Jedi was imported.

Most methods have a line and a column parameter. Lines in Jedi are always 1-based and columns are always zero based. To avoid repetition they are not always documented. You can omit both line and column. Jedi will then just do whatever action you are calling at the end of the file. If you provide only the line, just will complete at the end of that line.

Warning

By default jedi.settings.fast_parser is enabled, which means that parso reuses modules (i.e. they are not immutable). With this setting Jedi is not thread safe and it is also not safe to use multiple Script instances and its definitions at the same time.

If you are a normal plugin developer this should not be an issue. It is an issue for people that do more complex stuff with Jedi.

This is purely a performance optimization and works pretty well for all typical usages, however consider to turn the setting of if it causes you problems. See also this discussion.

Parameters:
  • code (str) – The source code of the current file, separated by newlines.
  • line (int) – Deprecated, please use it directly on e.g. .complete
  • column (int) – Deprecated, please use it directly on e.g. .complete
  • path (str or None) – The path of the file in the file system, or '' if it hasn’t been saved yet.
  • encoding (str) – Deprecated, cast to unicode yourself. The encoding of code, if it is not a unicode object (default 'utf-8').
  • sys_path (typing.List[str]) – Deprecated, use the project parameter.
  • environment (Environment) – Provide a predefined Environment to work with a specific Python version or virtualenv.
  • project (Project) – Provide a Project to make sure finding references works well, because the right folder is searched. There are also ways to modify the sys path and other things.
complete(line=None, column=None, **kwargs)[source]

Completes objects under the cursor.

Those objects contain information about the completions, more than just names.

Parameters:fuzzy – Default False. Will return fuzzy completions, which means that e.g. ooa will match foobar.
Returns:Completion objects, sorted by name. Normal names appear before “private” names that start with _ and those appear before magic methods and name mangled names that start with __.
Return type:list of Completion
infer(line=None, column=None, **kwargs)[source]

Return the definitions of under the cursor. It is basically a wrapper around Jedi’s type inference.

This method follows complicated paths and returns the end, not the first definition. The big difference between goto() and infer() is that goto() doesn’t follow imports and statements. Multiple objects may be returned, because depending on an option you can have two different versions of a function.

Parameters:
  • only_stubs – Only return stubs for this method.
  • prefer_stubs – Prefer stubs to Python objects for this method.
Return type:

list of Name

goto(line=None, column=None, **kwargs)[source]

Goes to the name that defined the object under the cursor. Optionally you can follow imports. Multiple objects may be returned, depending on an if you can have two different versions of a function.

Parameters:
  • follow_imports – The method will follow imports.
  • follow_builtin_imports – If follow_imports is True will try to look up names in builtins (i.e. compiled or extension modules).
  • only_stubs – Only return stubs for this method.
  • prefer_stubs – Prefer stubs to Python objects for this method.
Return type:

list of Name

search(string, **kwargs)[source]

Searches a name in the current file. For a description of how the search string should look like, please have a look at Project.search().

Parameters:all_scopes (bool) – Default False; searches not only for definitions on the top level of a module level, but also in functions and classes.
Yields:Name

Like Script.search(), but completes that string. If you want to have all possible definitions in a file you can also provide an empty string.

Parameters:
  • all_scopes (bool) – Default False; searches not only for definitions on the top level of a module level, but also in functions and classes.
  • fuzzy – Default False. Will return fuzzy completions, which means that e.g. ooa will match foobar.
Yields:

Completion

help(line=None, column=None)[source]

Used to display a help window to users. Uses Script.goto() and returns additional definitions for keywords and operators.

Typically you will want to display BaseName.docstring() to the user for all the returned definitions.

The additional definitions are Name(...).type == 'keyword'. These definitions do not have a lot of value apart from their docstring attribute, which contains the output of Python’s help() function.

Return type:list of Name
get_references(line=None, column=None, **kwargs)[source]

Lists all references of a variable in a project. Since this can be quite hard to do for Jedi, if it is too complicated, Jedi will stop searching.

Parameters:include_builtins – Default True, checks if a reference is a builtin (e.g. sys) and in that case does not return it.
Return type:list of Name
get_signatures(line=None, column=None)[source]

Return the function object of the call under the cursor.

E.g. if the cursor is here:

abs(# <-- cursor is here

This would return the abs function. On the other hand:

abs()# <-- cursor is here

This would return an empty list..

Return type:list of Signature
get_context(line=None, column=None)[source]

Returns the scope context under the cursor. This basically means the function, class or module where the cursor is at.

Return type:Name
get_names(**kwargs)[source]

Returns names defined in the current file.

Parameters:
  • all_scopes – If True lists the names of all scopes instead of only the module namespace.
  • definitions – If True lists the names that have been defined by a class, function or a statement (a = b returns a).
  • references – If True lists all the names that are not listed by definitions=True. E.g. a = b returns b.
Return type:

list of Name

get_syntax_errors()[source]

Lists all syntax errors in the current file.

Return type:list of SyntaxError
rename(line=None, column=None, **kwargs)[source]

Renames all references of the variable under the cursor.

Parameters:new_name – The variable under the cursor will be renamed to this string.
Raises:RefactoringError
Return type:Refactoring
extract_variable(line, column, **kwargs)[source]

Moves an expression to a new statemenet.

For example if you have the cursor on foo and provide a new_name called bar:

foo = 3.1
x = int(foo + 1)

the code above will become:

foo = 3.1
bar = foo + 1
x = int(bar)
Parameters:
  • new_name – The expression under the cursor will be renamed to this string.
  • until_line (int) – The the selection range ends at this line, when omitted, Jedi will be clever and try to define the range itself.
  • until_column (int) – The the selection range ends at this column, when omitted, Jedi will be clever and try to define the range itself.
Raises:

RefactoringError

Return type:

Refactoring

extract_function(line, column, **kwargs)[source]

Moves an expression to a new function.

For example if you have the cursor on foo and provide a new_name called bar:

global_var = 3

def x():
    foo = 3.1
    x = int(foo + 1 + global_var)

the code above will become:

global_var = 3

def bar(foo):
    return foo + 1 + global_var

def x(foo):
    x = int(bar(foo))
Parameters:
  • new_name – The expression under the cursor will be replaced with a function with this name.
  • until_line (int) – The the selection range ends at this line, when omitted, Jedi will be clever and try to define the range itself.
  • until_column (int) – The the selection range ends at this column, when omitted, Jedi will be clever and try to define the range itself.
Raises:

RefactoringError

Return type:

Refactoring

inline(line=None, column=None)[source]

Inlines a variable under the cursor. This is basically the opposite of extracting a variable. For example with the cursor on bar:

foo = 3.1
bar = foo + 1
x = int(bar)

the code above will become:

foo = 3.1
x = int(foo + 1)
Raises:RefactoringError
Return type:Refactoring

Interpreter

class jedi.Interpreter(code, namespaces, **kwds)[source]

Jedi’s API for Python REPLs.

Implements all of the methods that are present in Script as well.

In addition to completions that normal REPL completion does like str.upper, Jedi also supports code completion based on static code analysis. For example Jedi will complete str().upper.

>>> from os.path import join
>>> namespace = locals()
>>> script = Interpreter('join("").up', [namespace])
>>> print(script.complete()[0].name)
upper

All keyword arguments are same as the arguments for Script.

Parameters:

Projects

Projects are a way to handle Python projects within Jedi. For simpler plugins you might not want to deal with projects, but if you want to give the user more flexibility to define sys paths and Python interpreters for a project, Project is the perfect way to allow for that.

Projects can be saved to disk and loaded again, to allow project definitions to be used across repositories.

jedi.get_default_project(path=None)[source]

If a project is not defined by the user, Jedi tries to define a project by itself as well as possible. Jedi traverses folders until it finds one of the following:

  1. A .jedi/config.json
  2. One of the following files: setup.py, .git, .hg, requirements.txt and MANIFEST.in.
class jedi.Project(path, **kwargs)[source]

Projects are a simple way to manage Python folders and define how Jedi does import resolution. It is mostly used as a parameter to Script. Additionally there are functions to search a whole project.

Parameters:
  • path – The base path for this project.
  • environment_path – The Python executable path, typically the path of a virtual environment.
  • load_unsafe_extensions – Default False, Loads extensions that are not in the sys path and in the local directories. With this option enabled, this is potentially unsafe if you clone a git repository and analyze it’s code, because those compiled extensions will be important and therefore have execution privileges.
  • sys_path – list of str. You can override the sys path if you want. By default the sys.path. is generated by the environment (virtualenvs, etc).
  • added_sys_path – list of str. Adds these paths at the end of the sys path.
  • smart_sys_path – If this is enabled (default), adds paths from local directories. Otherwise you will have to rely on your packages being properly configured on the sys.path.
classmethod load(path)[source]

Loads a project from a specific path. You should not provide the path to .jedi/project.json, but rather the path to the project folder.

Parameters:path – The path of the directory you want to use as a project.
save()[source]

Saves the project configuration in the project in .jedi/project.json.

search(string, **kwargs)[source]

Searches a name in the whole project. If the project is very big, at some point Jedi will stop searching. However it’s also very much recommended to not exhaust the generator. Just display the first ten results to the user.

There are currently three different search patterns:

  • foo to search for a definition foo in any file or a file called foo.py or foo.pyi.
  • foo.bar to search for the foo and then an attribute bar in it.
  • class foo.bar.Bar or def foo.bar.baz to search for a specific API type.
Parameters:all_scopes (bool) – Default False; searches not only for definitions on the top level of a module level, but also in functions and classes.
Yields:Name

Like Script.search(), but completes that string. An empty string lists all definitions in a project, so be careful with that.

Parameters:all_scopes (bool) – Default False; searches not only for definitions on the top level of a module level, but also in functions and classes.
Yields:Completion

Environments

Environments are a way to activate different Python versions or Virtualenvs for static analysis. The Python binary in that environment is going to be executed.

jedi.find_system_environments()[source]

Ignores virtualenvs and returns the Python versions that were installed on your system. This might return nothing, if you’re running Python e.g. from a portable version.

The environments are sorted from latest to oldest Python version.

Yields:Environment
jedi.find_virtualenvs(paths=None, **kwargs)[source]
Parameters:
  • paths – A list of paths in your file system to be scanned for Virtualenvs. It will search in these paths and potentially execute the Python binaries.
  • safe – Default True. In case this is False, it will allow this function to execute potential python environments. An attacker might be able to drop an executable in a path this function is searching by default. If the executable has not been installed by root, it will not be executed.
  • use_environment_vars – Default True. If True, the VIRTUAL_ENV variable will be checked if it contains a valid VirtualEnv. CONDA_PREFIX will be checked to see if it contains a valid conda environment.
Yields:

Environment

jedi.get_system_environment(version)[source]

Return the first Python environment found for a string of the form ‘X.Y’ where X and Y are the major and minor versions of Python.

Raises:InvalidPythonEnvironment
Returns:Environment
jedi.create_environment(path, safe=True)[source]

Make it possible to manually create an Environment object by specifying a Virtualenv path or an executable path.

Raises:InvalidPythonEnvironment
Returns:Environment
jedi.get_default_environment()[source]

Tries to return an active Virtualenv or conda environment. If there is no VIRTUAL_ENV variable or no CONDA_PREFIX variable set set it will return the latest Python version installed on the system. This makes it possible to use as many new Python features as possible when using autocompletion and other functionality.

Returns:Environment
exception jedi.InvalidPythonEnvironment[source]

If you see this exception, the Python executable or Virtualenv you have been trying to use is probably not a correct Python version.

class jedi.api.environment.Environment(executable)[source]

This class is supposed to be created by internal Jedi architecture. You should not create it directly. Please use create_environment or the other functions instead. It is then returned by that function.

get_sys_path()[source]

The sys path for this environment. Does not include potential modifications from e.g. appending to sys.path.

Returns:list of str

Helper Functions

jedi.preload_module(*modules)[source]

Preloading modules tells Jedi to load a module now, instead of lazy parsing of modules. This can be useful for IDEs, to control which modules to load on startup.

Parameters:modules – different module names, list of string.
jedi.set_debug_function(func_cb=<function print_to_stdout>, warnings=True, notices=True, speed=True)[source]

Define a callback debug function to get all the debug messages.

If you don’t specify any arguments, debug messages will be printed to stdout.

Parameters:func_cb – The callback function for debug messages.

Errors

exception jedi.InternalError[source]

This error might happen a subprocess is crashing. The reason for this is usually broken C code in third party libraries. This is not a very common thing and it is safe to use Jedi again. However using the same calls might result in the same error again.

exception jedi.RefactoringError[source]

Refactorings can fail for various reasons. So if you work with refactorings like Script.rename(), Script.inline(), Script.extract_variable() and Script.extract_function(), make sure to catch these. The descriptions in the errors are ususally valuable for end users.

A typical RefactoringError would tell the user that inlining is not possible if no name is under the cursor.

Examples

Completions

>>> import jedi
>>> code = '''import json; json.l'''
>>> script = jedi.Script(code, path='example.py')
>>> script
<Script: 'example.py' <SameEnvironment: 3.5.2 in /usr>>
>>> completions = script.complete(1, 19)
>>> completions
[<Completion: load>, <Completion: loads>]
>>> completions[1]
<Completion: loads>
>>> completions[1].complete
'oads'
>>> completions[1].name
'loads'

Type Inference / Goto

>>> import jedi
>>> code = '''\
... def my_func():
...     print 'called'
...
... alias = my_func
... my_list = [1, None, alias]
... inception = my_list[2]
...
... inception()'''
>>> script = jedi.Script(code)
>>>
>>> script.goto(8, 1)
[<Name full_name='__main__.inception', description='inception = my_list[2]'>]
>>>
>>> script.infer(8, 1)
[<Name full_name='__main__.my_func', description='def my_func'>]

References

>>> import jedi
>>> code = '''\
... x = 3
... if 1 == 2:
...     x = 4
... else:
...     del x'''
>>> script = jedi.Script(code)
>>> rns = script.get_references(5, 8)
>>> rns
[<Name full_name='__main__.x', description='x = 3'>,
 <Name full_name='__main__.x', description='x = 4'>,
 <Name full_name='__main__.x', description='del x'>]
>>> rns[1].line
3
>>> rns[1].column
4

Deprecations

The deprecation process is as follows:

  1. A deprecation is announced in the next major/minor release.
  2. We wait either at least a year and at least two minor releases until we remove the deprecated functionality.