### Manual Installation from GitHub Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/installation.rst Clone the Jedi repository from GitHub and install it manually using setup.py. This method is for users who prefer not to use automated package installers. ```bash git clone --recurse-submodules https://github.com/davidhalter/jedi cd jedi sudo python setup.py install ``` -------------------------------- ### Jedi Script Completion Example Source: https://context7.com/davidhalter/jedi/llms.txt Demonstrates how to use the `jedi.Script.complete` method to get code completions. This is useful for IDEs to provide suggestions as the user types. ```python import jedi source = """ import os def process(filepath: str) -> bytes: """Read a file and return its contents.""" with open(filepath, 'rb') as f: return f.read() process( """ script = jedi.Script(source, path='example.py') # --- Completion object properties --- completions = script.complete(2, 3) # 'os.' c = completions[0] print(c.name) # e.g. 'path' print(c.complete) # the suffix to append, e.g. 'ath' print(c.type) # 'module' / 'function' / 'class' / etc. print(c.name_with_symbols)# may include '=' for keyword args ``` -------------------------------- ### Install Graphviz Source: https://github.com/davidhalter/jedi/blob/master/docs/README.md Installs the graphviz library using apt-get. ```bash sudo apt-get install graphviz ``` -------------------------------- ### Install Sphinx Source: https://github.com/davidhalter/jedi/blob/master/docs/README.md Installs the sphinx documentation generator using pip. ```bash sudo pip install sphinx ``` -------------------------------- ### Install pytest Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/testing.rst Install the pytest testing framework using pip. This is a prerequisite for running Jedi's tests. ```bash pip install pytest ``` -------------------------------- ### Install Python Graphviz Interface Source: https://github.com/davidhalter/jedi/blob/master/docs/README.md Installs the Python interface for graphviz using pip. ```bash sudo pip install graphviz ``` -------------------------------- ### Install Jedi with Pip Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/installation.rst Use this command to install the Jedi library from the Python Package Index using pip. ```bash sudo pip install jedi ``` -------------------------------- ### Install Development Version with Pip Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/installation.rst Install the current development version of Jedi directly from the master branch on GitHub using pip. ```bash sudo pip install -e git+https://github.com/davidhalter/jedi.git#egg=jedi ``` -------------------------------- ### Jedi Script Infer Example Source: https://context7.com/davidhalter/jedi/llms.txt Shows how to use `jedi.Script.infer` to find definitions of variables or functions. This is the basis for jump-to-definition features. ```python names = script.infer(3, 5) # infer 'process' if names: n = names[0] print(n.name) # 'process' print(n.full_name) # '__main__.process' print(n.type) # 'function' print(n.line) # 3 print(n.column) # 0 print(n.module_name) # '__main__' print(n.module_path) # None (in-memory) or Path object print(n.is_definition())# True print(n.is_stub()) # False print(n.docstring()) # 'process(filepath: str) -> bytes\n\nRead a file...' print(n.docstring(raw=True)) # 'Read a file and return its contents.' print(n.description) # 'def process' print(n.get_type_hint()) # 'Callable[[str], bytes]' print(n.get_definition_start_position()) # (3, 0) print(n.get_definition_end_position()) # (6, 20) print(n.get_line_code()) # 'def process(filepath: str) -> bytes:\n' print(n.parent().name) # module name # sub-definitions: list methods/attributes of a class or module sub = n.defined_names() print([s.name for s in sub]) # follow a Name to its own goto/infer deeper = n.goto(follow_imports=True) print(deeper) ``` -------------------------------- ### Jedi Script Signature Example Source: https://context7.com/davidhalter/jedi/llms.txt Illustrates how to retrieve function signatures using `jedi.Script.get_signatures`. This is used for displaying argument hints when a function is called. ```python sigs = script.get_signatures(8, 8) # inside process( if sigs: sig = sigs[0] print(sig.name) # 'process' print(sig.index) # 0 — cursor at first param print(sig.bracket_start)# (8, 7) print(sig.to_string()) # 'process(filepath: str) -> bytes' for p in sig.params: print(p.name, p.to_string(), p.kind) # filepath filepath: str POSITIONAL_OR_KEYWORD ``` -------------------------------- ### Get Completions for Code Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/api.rst Use Script.complete to get a list of possible completions at a specific cursor position within a code string. Requires importing jedi and creating a Script object. ```python >>> import jedi >>> code = '''import json; json.l''' >>> script = jedi.Script(code, path='example.py') >>> script > >>> completions = script.complete(1, 19) >>> completions [, ] >>> completions[1] >>> completions[1].complete 'oads' >>> completions[1].name 'loads' ``` -------------------------------- ### Numpydoc Style Type Hinting Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/usage.rst Example of using Numpydoc format for function documentation, which can indirectly aid type hinting. Requires the 'numpydoc' package. ```python def foo(var1, var2, long_var_name='hi'): r""" ``` -------------------------------- ### In-file code search with Jedi Source: https://context7.com/davidhalter/jedi/llms.txt Use `Script.search` and `Script.complete_search` to find definitions within the current file. `search` finds exact matches, while `complete_search` lists names starting with a given prefix. ```python import jedi source = """ class HttpClient: def get(self, url): pass def post(self, url, data): pass class HttpServer: def listen(self, port): pass def create_client(): return HttpClient() """ script = jedi.Script(source) # Find definitions matching 'Http' results = list(script.search('Http')) for r in results: print(r.name, r.type, r.line) # HttpClient class 1 # HttpServer class 5 # Search for a specific type classes = list(script.search('class Http')) print([c.name for c in classes]) # ['HttpClient', 'HttpServer'] # Complete-search: list names starting with 'Http' completions = list(script.complete_search('Http')) print([c.name for c in completions]) # ['HttpClient', 'HttpServer'] ``` -------------------------------- ### Autocompletion with Script.complete Source: https://context7.com/davidhalter/jedi/llms.txt Use the `complete` method to get a list of `Completion` objects for the expression under the cursor. Supports optional fuzzy matching. ```python import jedi source = "import json\njson.lo" script = jedi.Script(source, path='example.py') # Complete at line 2, column 7 (after "json.lo") completions = script.complete(2, 7) print(completions) for c in completions: print(c.name, '|', c.complete, '|', c.type) ``` ```python # Fuzzy completion: "jlo" can match "json.loads" source2 = "import json\njson.jlo" script2 = jedi.Script(source2) fuzzy_completions = script2.complete(2, 8, fuzzy=True) print([c.name for c in fuzzy_completions]) ``` -------------------------------- ### Get References with Scope and Built-in Filtering Source: https://context7.com/davidhalter/jedi/llms.txt Retrieves references within a specific file scope and demonstrates excluding built-in modules. ```python import jedi source = "" x = 4 """ script = jedi.Script(source) refs = script.get_references(1, 0) for ref in refs: print(f"line={ref.line}, col={ref.column}, is_def={ref.is_definition()}") # line=1, col=0, is_def=True # line=3, col=4, is_def=True # line=5, col=8, is_def=False # Restrict to current file only file_refs = script.get_references(1, 0, scope='file') # Exclude builtins no_builtins = script.get_references(1, 0, include_builtins=False) ``` -------------------------------- ### Initialize Jedi Script Source: https://context7.com/davidhalter/jedi/llms.txt Instantiate the Script class with Python source code and an optional file path. Lines are 1-based, columns are 0-based. Omitting line/column defaults to the end of the source. ```python import jedi source = """ import os import json def process(data: dict) -> str: result = json.dumps(data) return os.path.join('/tmp', result) process( """ script = jedi.Script(source, path='example.py') print(repr(script)) ``` -------------------------------- ### Go-to Definition with Script.goto Source: https://context7.com/davidhalter/jedi/llms.txt Returns the definition site of the name under the cursor. By default, it does not follow imports. Set `follow_imports=True` to resolve through imports and `follow_builtin_imports=True` for built-in imports. ```python import jedi source = """ import os result = os.path.join('/tmp', 'file.txt') """ script = jedi.Script(source, path='example.py') # Without follow_imports: stops at the import names = script.goto(2, 10) print(names) # With follow_imports: resolves through to the actual module file names_deep = script.goto(2, 10, follow_imports=True, follow_builtin_imports=True) print(names_deep) # Goto a function attribute names_join = script.goto(2, 14, follow_imports=True) print(names_join) print(names_join[0].module_path) ``` -------------------------------- ### Script.rename Source: https://context7.com/davidhalter/jedi/llms.txt Renames a function or variable at a specific cursor position. It returns a refactoring object that can be used to get the diff or apply the changes. ```APIDOC ## Script.rename Renames a function or variable at a specific cursor position. ```python import jedi source = """\ndef calculate_total(items): return sum(items) result = calculate_total([1, 2, 3]) print(calculate_total([4, 5])) """ script = jedi.Script(source, path='mymodule.py') # Rename 'calculate_total' to 'compute_sum' at line 1, col 4 refactoring = script.rename(1, 4, new_name='compute_sum') print(refactoring.get_diff()) ``` ### Parameters - **new_name** (str) - The new name for the function or variable. ``` -------------------------------- ### Script.help Source: https://context7.com/davidhalter/jedi/llms.txt Looks up documentation for Python keywords, operators, or definitions at the cursor, returning their help docstrings. ```APIDOC ## Script.help ### Description Like `goto` but also handles Python keywords and operators, returning their `help()` docstrings. Intended to power "show documentation" hover actions in editors. ### Method `script.help(line: int, column: int)` ### Parameters #### Path Parameters - **line** (int) - The line number of the cursor. - **column** (int) - The column number of the cursor. #### Query Parameters None #### Request Body None ### Request Example ```python import jedi source = "import os\nos.getcwd" script = jedi.Script(source, path='example.py') # Get docs for os.getcwd definitions = script.help(2, 5) for d in definitions: print(d.name) print(d.docstring()[:120]) # Keywords also work kw_script = jedi.Script("for") kw_defs = kw_script.help(1, 2) print(kw_defs[0].type) print(kw_defs[0].name) ``` ### Response #### Success Response (200) - **definitions** (list[Definition]) - A list of Definition objects containing documentation. #### Response Example ``` getcwd getcwd() -> str Return a unicode string representing the current working directory. keyword for ``` ### Additional Information - `Definition.name`: The name of the definition. - `Definition.docstring()`: Returns the docstring. - `Definition.type`: The type of the definition (e.g., 'keyword', 'function'). ``` -------------------------------- ### Project-wide analysis with jedi.Project Source: https://context7.com/davidhalter/jedi/llms.txt The `jedi.Project` class manages the root directory and sys path for multi-file analysis. It enables project-wide reference searching and is passed to `jedi.Script` for context. ```python import jedi from pathlib import Path # Create a project rooted at the current directory project = jedi.Project(path='.', added_sys_path=['/opt/mylibs']) print(project) # # Use the project with a Script script = jedi.Script( "import mymodule\nmymodule.", path='main.py', project=project ) completions = script.complete(2, 10) ``` -------------------------------- ### Project Search and Completion Source: https://context7.com/davidhalter/jedi/llms.txt Perform searches for class names or attributes within a project. Also demonstrates project configuration saving and loading. ```python results = list(project.search('class MyService')) for r in results: print(r.name, r.module_path, r.line) ``` ```python results2 = list(project.search('foo.bar')) for r in results2: print(r.full_name) ``` ```python completions2 = list(project.complete_search('MyS')) print([c.name for c in completions2[:5]]) ``` ```python project.save() # writes .jedi/project.json loaded = jedi.Project.load('.') print(loaded.path) ``` -------------------------------- ### Get Scope Context at Cursor Source: https://context7.com/davidhalter/jedi/llms.txt Determines the innermost enclosing scope (module, class, or function) at a given cursor position. Useful for understanding the current code context. ```python import jedi source = """ class MyClass: def my_method(self): x = 1 return x """ script = jedi.Script(source) # Cursor inside my_method body ctx = script.get_context(3, 8) print(ctx.name) # 'my_method' print(ctx.type) # 'function' # Cursor on class line ctx2 = script.get_context(1, 6) print(ctx2.name) # 'MyClass' print(ctx2.type) # 'class' # Cursor at module level ctx3 = script.get_context(1, 0) print(ctx3.type) # 'module' ``` -------------------------------- ### Script.goto Source: https://context7.com/davidhalter/jedi/llms.txt Retrieves the definition site of the name under the cursor. By default, it does not follow imports, but can be configured to do so. ```APIDOC ## `Script.goto` — Go-to definition Returns the definition site of the name under the cursor. Unlike `infer`, it does not follow imports by default, returning the import statement itself. Set `follow_imports=True` to jump through imports. ```python import jedi source = """ import os result = os.path.join('/tmp', 'file.txt') """ script = jedi.Script(source, path='example.py') # Without follow_imports: stops at the import names = script.goto(2, 10) print(names) # [] # With follow_imports: resolves through to the actual module file names_deep = script.goto(2, 10, follow_imports=True, follow_builtin_imports=True) print(names_deep) # [] # Goto a function attribute names_join = script.goto(2, 14, follow_imports=True) print(names_join) # [] print(names_join[0].module_path) # /usr/lib/python3.12/posixpath.py (or similar) ``` ``` -------------------------------- ### Get Function Call Signatures Source: https://context7.com/davidhalter/jedi/llms.txt Retrieves `Signature` objects for the function call at the cursor position, useful for argument hint tooltips. Ensure the cursor is within a function call. ```python import jedi source = "import json\njson.dumps({'key': 'val'}, " script = jedi.Script(source) # Cursor is inside the call to json.dumps sigs = script.get_signatures(2, len("json.dumps({'key': 'val'}, ")) print(sigs) # [] sig = sigs[0] print(sig.name) # 'dumps' print(sig.index) # 1 (cursor is at the second argument) print(sig.bracket_start) # (2, 10) — (line, column) of the opening '(' print(sig.to_string()) # 'dumps(obj, *, skipkeys=False, ensure_ascii=True, ...)' for param in sig.params: print(param.name, param.kind) # obj POSITIONAL_OR_KEYWORD # skipkeys KEYWORD_ONLY # ... ``` -------------------------------- ### jedi.Project Source: https://context7.com/davidhalter/jedi/llms.txt Manages the root directory and sys path for multi-file analysis. It enables project-wide reference search and is passed as a parameter to `Script`. ```APIDOC ## jedi.Project — Project-wide search and configuration `Project` manages the root directory and sys path for multi-file analysis. It enables project-wide reference search and is passed as a parameter to `Script`. ```python import jedi from pathlib import Path # Create a project rooted at the current directory project = jedi.Project(path='.', added_sys_path=['/opt/mylibs']) print(project) # # Use the project with a Script script = jedi.Script( "import mymodule\nmymodule.", path='main.py', project=project ) completions = script.complete(2, 10) ``` ### Parameters - **path** (str) - The root path of the project. - **added_sys_path** (list[str], optional) - Additional paths to include in sys.path for analysis. ``` -------------------------------- ### Script.goto Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/api.rst Finds definitions for a given position in a script. ```APIDOC ## Script.goto ### Description Finds definitions for a given position in a script. ### Method Script.goto ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import jedi code = '''def my_func():\n print \'called\'\n\nalias = my_func\nmy_list = [1, None, alias]\ninception = my_list[2]\n\ninception()''' script = jedi.Script(code) script.goto(8, 1) ``` ### Response #### Success Response (200) - **definitions** (list) - A list of Name objects representing definitions. #### Response Example ```json [ { "full_name": "__main__.inception", "description": "inception = my_list[2]" } ] ``` ``` -------------------------------- ### Type Inference with Script.infer Source: https://context7.com/davidhalter/jedi/llms.txt The `infer` method follows the inference chain from the symbol under the cursor, returning `Name` objects representing actual types/definitions, even through imports and assignments. Use `goto` to get the local assignment. ```python import jedi source = """ def my_func(): pass alias = my_func my_list = [1, None, alias] inception = my_list[2] inception()""" script = jedi.Script(source) # goto returns the local assignment, infer follows to the original function goto_result = script.goto(8, 1) print(goto_result) infer_result = script.infer(8, 1) print(infer_result) name = infer_result[0] print(name.type) print(name.full_name) print(name.module_path) print(name.line) print(name.docstring()) ``` -------------------------------- ### jedi.find_system_environments Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/api.rst Finds all available system Python environments. ```APIDOC ## jedi.find_system_environments ### Description Finds all available system Python environments. ### Method jedi.find_system_environments ### Parameters None ### Request Example ```python import jedi jedi.find_system_environments() ``` ### Response #### Success Response (200) - **environments** (list) - A list of Environment objects. #### Response Example ```json [ { "python_executable": "/usr/bin/python3", "version": "3.10.0" } ] ``` ``` -------------------------------- ### Assignment, For-loop, and With-statement Type Hints Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/usage.rst Demonstrates type hints for variables, loop iterables, and context managers using PEP 484. ```python import typing x: int = foo() y: typing.Optional[int] = 3 key: str value: Employee for key, value in foo.items(): pass f: Union[int, float] with foo() as f: print(f + 3) ``` -------------------------------- ### jedi.get_default_project Source: https://context7.com/davidhalter/jedi/llms.txt Auto-detects the project root by traversing the directory tree upward and returns a `Project` instance. It can detect project roots by looking for markers like `.git`, `setup.py`, or `pyproject.toml`. ```APIDOC ## `jedi.get_default_project` — Auto-detect project root Traverses the directory tree upward to find a project root (by detecting `.git`, `setup.py`, `pyproject.toml`, etc.) and returns a `Project` instance. ```python import jedi from pathlib import Path # Auto-detect from the current working directory project = jedi.get_default_project() print(project) # # Auto-detect from a specific file's directory project2 = jedi.get_default_project(Path('/home/user/myproject/src/mymodule.py').parent) print(project2) # # Use the auto-detected project in a script script = jedi.Script( "import os\nos.path.", path='/home/user/myproject/src/main.py', project=project ) ``` ``` -------------------------------- ### Auto-detect Project Root with jedi.get_default_project Source: https://context7.com/davidhalter/jedi/llms.txt Automatically detects the project root directory by searching for common project markers like .git or pyproject.toml. Can be used from the current directory or a specified path. ```python import jedi from pathlib import Path # Auto-detect from the current working directory project = jedi.get_default_project() print(project) # ``` ```python # Auto-detect from a specific file's directory project2 = jedi.get_default_project(Path('/home/user/myproject/src/mymodule.py').parent) print(project2) # ``` ```python # Use the auto-detected project in a script script = jedi.Script( "import os\nos.path.", path='/home/user/myproject/src/main.py', project=project ) ``` -------------------------------- ### Lookup Documentation for Keywords and Functions Source: https://context7.com/davidhalter/jedi/llms.txt Retrieves documentation strings for Python keywords, operators, and function calls. Useful for hover documentation features. The `path` argument is recommended for accurate results. ```python import jedi source = "import os\nos.getcwd" script = jedi.Script(source, path='example.py') # Get docs for os.getcwd definitions = script.help(2, 5) for d in definitions: print(d.name) print(d.docstring()[:120]) # getcwd # getcwd() -> str # # Return a unicode string representing the current working directory. # Keywords also work kw_script = jedi.Script("for") kw_defs = kw_script.help(1, 2) print(kw_defs[0].type) # 'keyword' print(kw_defs[0].name) # 'for' ``` -------------------------------- ### jedi.Script Source: https://context7.com/davidhalter/jedi/llms.txt The main entry point for Jedi's static analysis. It accepts Python source code and provides methods for various code intelligence features. ```APIDOC ## `jedi.Script` — Main analysis entry point `Script` is the primary API class. It accepts Python source code (and optionally a file path) and exposes all analysis methods. Lines are 1-based, columns are 0-based. Omitting `line`/`column` defaults to the end of the source. ```python import jedi source = """ import os import json def process(data: dict) -> str: result = json.dumps(data) return os.path.join('/tmp', result) process( """ script = jedi.Script(source, path='example.py') print(repr(script)) # > ``` ``` -------------------------------- ### Live namespace completion with jedi.Interpreter Source: https://context7.com/davidhalter/jedi/llms.txt The `jedi.Interpreter` class enables live namespace completion, similar to REPLs. It uses provided namespace dictionaries for type inference, making it suitable for interactive environments. ```python import jedi # Simulate a REPL where the user has already defined some objects class MyClass: def greet(self): return "hello" my_attr = 42 obj = MyClass() namespace = {'obj': obj, 'MyClass': MyClass} # Complete "obj." using the live namespace interpreter = jedi.Interpreter('obj.', [namespace]) completions = interpreter.complete(1, 4) print([c.name for c in completions]) # ['greet', 'my_attr', ...] # Multi-level namespace: locals() inside a function def my_function(): local_list = [1, 2, 3] interp = jedi.Interpreter('local_list.app', [locals()]) result = interp.complete(1, len('local_list.app')) print([c.name for c in result]) # ['append'] my_function() ``` -------------------------------- ### jedi.Interpreter Source: https://context7.com/davidhalter/jedi/llms.txt Works like `Script` but additionally uses live Python namespace dictionaries for type inference. Ideal for implementing completions in REPLs (IPython, ptpython, etc.). ```APIDOC ## jedi.Interpreter — REPL / live namespace completion `Interpreter` works like `Script` but additionally uses live Python namespace dictionaries for type inference. Ideal for implementing completions in REPLs (IPython, ptpython, etc.). ```python import jedi # Simulate a REPL where the user has already defined some objects class MyClass: def greet(self): return "hello" my_attr = 42 obj = MyClass() namespace = {'obj': obj, 'MyClass': MyClass} # Complete "obj." using the live namespace interpreter = jedi.Interpreter('obj.', [namespace]) completions = interpreter.complete(1, 4) print([c.name for c in completions]) # ['greet', 'my_attr', ...] # Multi-level namespace: locals() inside a function def my_function(): local_list = [1, 2, 3] interp = jedi.Interpreter('local_list.app', [locals()]) result = interp.complete(1, len('local_list.app')) print([c.name for c in result]) # ['append'] my_function() ``` ### Parameters - **code_to_complete** (str) - The code string to complete. - **namespaces** (list[dict]) - A list of dictionaries representing the live Python namespaces. ``` -------------------------------- ### Script.complete Source: https://context7.com/davidhalter/jedi/llms.txt Returns a list of `Completion` objects for the expression under the cursor, enabling autocompletion. Supports optional fuzzy matching. ```APIDOC ## `Script.complete` — Autocompletion Returns a list of `Completion` objects for the expression under the cursor. Supports optional fuzzy matching. ```python import jedi source = "import json\njson.lo" script = jedi.Script(source, path='example.py') # Complete at line 2, column 7 (after "json.lo") completions = script.complete(2, 7) print(completions) # [, ] for c in completions: print(c.name, '|', c.complete, '|', c.type) # load | ad | function # loads | ads | function # Fuzzy completion: "jlo" can match "json.loads" source2 = "import json\njson.jlo" script2 = jedi.Script(source2) fuzzy_completions = script2.complete(2, 8, fuzzy=True) print([c.name for c in fuzzy_completions]) # May include: ['loads', 'load', ...] ``` ``` -------------------------------- ### Load Jedi Extension in xonsh Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/usage.rst To enable Jedi autocompletion in the xonsh shell, load the 'jedi' extension. ```shell xontrib load jedi ``` -------------------------------- ### Configure Global Settings with jedi.settings Source: https://context7.com/davidhalter/jedi/llms.txt Modify module-level variables to control Jedi's global behavior, such as completion case sensitivity and function bracket addition. ```python from jedi import settings # Case-insensitive completions (default: True) settings.case_insensitive_completion = False # Automatically append '(' after function completions (default: False) settings.add_bracket_after_function = True # Disable diff-based parser (use for thread safety) (default: True) settings.fast_parser = False # Dynamic analysis of array mutations like .append() (default: True) settings.dynamic_array_additions = True # Dynamic parameter inference by finding call sites (default: True) settings.dynamic_params = True # Cache directory (platform-specific default) print(settings.cache_directory) # /home/user/.cache/jedi (Linux) # ~/Library/Caches/Jedi (macOS) ``` -------------------------------- ### jedi.preload_module Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/api.rst Preloads a module to improve completion performance. ```APIDOC ## jedi.preload_module ### Description Preloads a module to improve completion performance. ### Method jedi.preload_module ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import jedi jedi.preload_module('my_module') ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Type Inference and Goto Definition Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/api.rst Use Script.goto to find the definition of a name at a specific line and column, and Script.infer to determine the type of an expression. Both require a Script object initialized with code. ```python >>> 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) [] >>> >>> script.infer(8, 1) [] ``` -------------------------------- ### Script.get_references Source: https://context7.com/davidhalter/jedi/llms.txt Finds all usages of the symbol under the cursor. It searches the entire project by default, but can be scoped to the current file. ```APIDOC ## `Script.get_references` — Find all references Returns all usages of the symbol under the cursor. Searches the whole project by default; use `scope='file'` to restrict to the current file. ```python import jedi source = """ x = 3 if 1 == 2: x = 4 else: del x """ script = jedi.Script(source) refs = script.get_references(5, 8) # cursor on 'x' in 'del x' print(refs) # [, ``` -------------------------------- ### Function Annotations for Type Hinting Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/usage.rst Use function annotations as per PEP 484 for gradual typing. This is the recommended approach for type hinting. ```python def myfunction(node: ProgramNode, foo: str) -> None: """Do something with a ``node``. """ node.| # complete here ``` -------------------------------- ### Preload Modules for Performance with jedi.preload_module Source: https://context7.com/davidhalter/jedi/llms.txt Eagerly parses and caches modules to improve the speed of subsequent completion requests. Useful for common libraries in IDEs. ```python import jedi # Preload commonly used libraries at IDE startup jedi.preload_module('numpy', 'pandas', 'os', 'sys', 'typing') # Subsequent completions for these modules will be instant script = jedi.Script("import numpy\nnumpy.arr") completions = script.complete(2, 9) print([c.name for c in completions[:5]]) # ['array', 'argsort', 'around', ...] ``` -------------------------------- ### Discover Python Environments with jedi.find_system_environments Source: https://context7.com/davidhalter/jedi/llms.txt Enumerates available Python interpreters on the system and in specified directories. Useful for analyzing code with different Python versions or virtualenvs. ```python import jedi # List all system-installed Python versions (3.10–3.14) for env in jedi.find_system_environments(): print(env) # # ``` ```python # Discover virtualenvs in specific directories for env in jedi.find_virtualenvs(paths=['~/.virtualenvs', '.venv']): print(env.executable, env.version_info) ``` ```python # Get a specific version try: env311 = jedi.get_system_environment('3.11') print(env311.get_sys_path()[:3]) except jedi.InvalidPythonEnvironment as e: print(f"Not found: {e}") ``` ```python # Create an environment from a virtualenv path try: venv_env = jedi.create_environment('/home/user/projects/myapp/.venv') script = jedi.Script( "import requests\nrequests.", path='app.py', environment=venv_env ) completions = script.complete(2, 9) print([c.name for c in completions[:5]]) except jedi.InvalidPythonEnvironment as e: print(f"Invalid environment: {e}") ``` ```python # Get the active virtualenv or default environment default_env = jedi.get_default_environment() print(default_env) ``` -------------------------------- ### Script.complete Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/api.rst Provides code completions for a given position in a script. ```APIDOC ## Script.complete ### Description Provides code completions for a given position in a script. ### Method Script.complete ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import jedi code = '''import json; json.l''' script = jedi.Script(code, path='example.py') completions = script.complete(1, 19) ``` ### Response #### Success Response (200) - **completions** (list) - A list of completion objects. #### Response Example ```json [ { "completion": "load", "name": "load" }, { "completion": "loads", "name": "loads" } ] ``` ``` -------------------------------- ### Find References with Script.get_references Source: https://context7.com/davidhalter/jedi/llms.txt Returns all usages of the symbol under the cursor. Searches the whole project by default; use `scope='file'` to restrict to the current file. ```python import jedi source = """ x = 3 if 1 == 2: x = 4 else: del x """ script = jedi.Script(source) refs = script.get_references(5, 8) # cursor on 'x' in 'del x' print(refs) ``` -------------------------------- ### Configure Jedi Settings Source: https://context7.com/davidhalter/jedi/llms.txt Adjust caching and auto-import settings for Jedi. `call_signatures_validity` controls how long call signatures are cached, and `auto_import_modules` specifies modules to be auto-imported. ```python settings.call_signatures_validity = 5.0 settings.auto_import_modules = ['gi', 'cffi'] ``` -------------------------------- ### jedi.find_virtualenvs Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/api.rst Finds all available virtual environments. ```APIDOC ## jedi.find_virtualenvs ### Description Finds all available virtual environments. ### Method jedi.find_virtualenvs ### Parameters None ### Request Example ```python import jedi jedi.find_virtualenvs() ``` ### Response #### Success Response (200) - **virtualenvs** (list) - A list of Environment objects representing virtual environments. #### Response Example ```json [ { "python_executable": "/path/to/venv/bin/python", "version": "3.9.0" } ] ``` ``` -------------------------------- ### jedi.find_system_environments / jedi.find_virtualenvs Source: https://context7.com/davidhalter/jedi/llms.txt Functions to enumerate available Python interpreters. These can be used to pass an `Environment` to `Script` for analyzing code targeting different Python versions or virtualenvs. ```APIDOC ## `jedi.find_system_environments` / `jedi.find_virtualenvs` — Environment discovery Functions to enumerate available Python interpreters. Pass an `Environment` to `Script` to analyze code targeting a different Python version or virtualenv. ```python import jedi # List all system-installed Python versions (3.10–3.14) for env in jedi.find_system_environments(): print(env) # # # Discover virtualenvs in specific directories for env in jedi.find_virtualenvs(paths=['~/.virtualenvs', '.venv']): print(env.executable, env.version_info) # Get a specific version try: env311 = jedi.get_system_environment('3.11') print(env311.get_sys_path()[:3]) except jedi.InvalidPythonEnvironment as e: print(f"Not found: {e}") # Create an environment from a virtualenv path try: venv_env = jedi.create_environment('/home/user/projects/myapp/.venv') script = jedi.Script( "import requests\nrequests.", path='app.py', environment=venv_env ) completions = script.complete(2, 9) print([c.name for c in completions[:5]]) except jedi.InvalidPythonEnvironment as e: print(f"Invalid environment: {e}") # Get the active virtualenv or default environment default_env = jedi.get_default_environment() print(default_env) ``` ``` -------------------------------- ### Project.search Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/api.rst Searches for definitions within a project. ```APIDOC ## Project.search ### Description Searches for definitions within a project. ### Method Project.search ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import jedi project = jedi.get_default_project() results = project.search('my_variable') ``` ### Response #### Success Response (200) - **results** (list) - A list of Name objects found. #### Response Example ```json [ { "full_name": "__main__.my_variable", "description": "my_variable = 10" } ] ``` ``` -------------------------------- ### Sphinx Style Type Hinting Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/usage.rst Use Sphinx-style docstrings with ':type' and ':param' fields for type hinting. This is a less recommended approach compared to gradual typing. ```python def myfunction(node, foo): """ Do something with a ``node``. :type node: ProgramNode :param str foo: foo parameter description """ node.| # complete here ``` -------------------------------- ### Completion Object Properties Source: https://context7.com/davidhalter/jedi/llms.txt Demonstrates how to access properties of a completion object returned by the `Script.complete()` method. ```APIDOC ## Completion Object Properties This section details the properties available on completion objects returned by `jedi.Script.complete()`. ### Properties - **name** (string) - The name of the completion suggestion. - **complete** (string) - The suffix to append to the current text. - **type** (string) - The type of the completion (e.g., 'module', 'function', 'class'). - **name_with_symbols** (string) - The name possibly including symbols for keyword arguments. ``` -------------------------------- ### Project.complete_search Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/api.rst Searches for completions within a project. ```APIDOC ## Project.complete_search ### Description Searches for completions within a project. ### Method Project.complete_search ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import jedi project = jedi.get_default_project() completions = project.complete_search('my_module.') ``` ### Response #### Success Response (200) - **completions** (list) - A list of completion objects. #### Response Example ```json [ { "completion": "my_function", "name": "my_function" } ] ``` ``` -------------------------------- ### jedi.settings Source: https://context7.com/davidhalter/jedi/llms.txt Module-level variables that control Jedi's behavior globally. These settings can be imported and modified directly to customize Jedi's functionality. ```APIDOC ## `jedi.settings` — Global configuration Module-level variables that control Jedi's behavior globally. Import and modify directly. ```python from jedi import settings # Case-insensitive completions (default: True) settings.case_insensitive_completion = False # Automatically append '(' after function completions (default: False) settings.add_bracket_after_function = True # Disable diff-based parser (use for thread safety) (default: True) settings.fast_parser = False # Dynamic analysis of array mutations like .append() (default: True) settings.dynamic_array_additions = True # Dynamic parameter inference by finding call sites (default: True) settings.dynamic_params = True # Cache directory (platform-specific default) print(settings.cache_directory) # /home/user/.cache/jedi (Linux) # ~/Library/Caches/Jedi (macOS) ``` ``` -------------------------------- ### Name Object Properties Source: https://context7.com/davidhalter/jedi/llms.txt Explains the properties of a Name object, which is returned by methods like `Script.infer()`, `Script.goto()`, and `Script.get_references()`. ```APIDOC ## Name Object Properties This section describes the properties of a Name object, obtained from Jedi's analysis methods. ### Properties - **name** (string) - The name of the identifier. - **full_name** (string) - The fully qualified name of the identifier. - **type** (string) - The type of the identifier (e.g., 'function', 'module'). - **line** (integer) - The line number where the identifier is defined. - **column** (integer) - The column number where the identifier is defined. - **module_name** (string) - The name of the module where the identifier is defined. - **module_path** (Path object or None) - The path to the module file. - **is_definition()** (boolean) - Returns True if this Name object represents a definition. - **is_stub()** (boolean) - Returns True if the definition comes from a stub file. - **docstring()** (string) - Returns the docstring of the identifier. - **docstring(raw=True)** (string) - Returns the raw docstring content. - **description** (string) - A short description of the identifier (e.g., 'def function_name'). - **get_type_hint()** (string) - Returns the type hint for the identifier. - **get_definition_start_position()** (tuple) - Returns the start position (line, column) of the definition. - **get_definition_end_position()** (tuple) - Returns the end position (line, column) of the definition. - **get_line_code()** (string) - Returns the code of the line where the identifier is defined. - **parent()** (Name object) - Returns the parent Name object (e.g., the module for a function). ### Methods - **defined_names()** - Returns a list of sub-definitions (e.g., methods of a class). - **goto(follow_imports=True)** - Follows imports or definitions to the target Name object. ``` -------------------------------- ### jedi.api.classes.Completion Source: https://github.com/davidhalter/jedi/blob/master/docs/docs/api-classes.rst Represents a possible completion suggestion in an IDE. It includes details about the completion, such as its name, type, and documentation. ```APIDOC ## Class: jedi.api.classes.Completion ### Description Represents a possible completion suggestion in an IDE. It includes details about the completion, such as its name, type, and documentation. ### Members (Members are inherited and not explicitly listed here, refer to the source for details.) ``` -------------------------------- ### Update Typeshed in Jedi Source: https://github.com/davidhalter/jedi/blob/master/jedi/third_party/README_typeshed.md Follow these Git commands to update the Typeshed fork used by Jedi. Ensure you are in the correct directory and handle merge conflicts by prioritizing Jedi's commit. ```bash cd jedi/third_party/typeshed git remote add upstream https://github.com/python/typeshed git fetch upstream git checkout jedi git rebase upstream/master git push -f git push cd ../../.. git commit jedi/third_party/typeshed -m "Upgrade typeshed" ```