A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: interactive key completion (#5618)
Thierry Jean3e9c1aecdce6
diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.pyindex 726e6ea223..4f378023f7 100644--- a/marimo/_runtime/complete.py+++ b/marimo/_runtime/complete.py@@ -2,10 +2,12 @@from __future__ import annotationsimport html+import sysimport threadingimport time+from collections.abc import Collection, Mappingfrom functools import lru_cache-from typing import TYPE_CHECKING, Any, cast+from typing import TYPE_CHECKING, Any, Protocol, castimport jedi # type: ignore # noqa: F401import jedi.api # type: ignore # noqa: F401@@ -25,6 +27,7 @@ from marimo._utils.rst_to_html import convert_rst_to_htmlif TYPE_CHECKING:import threading+ from types import ModuleTypeLOGGER = loggers.marimo_logger()@@ -344,6 +347,133 @@ def _get_completions_with_interpreter(return script, completions+# TODO move this to a global utility module+def _isinstance_external(obj: Any, *, class_ref: str) -> bool:+ """Check if an object is an instance of a class reference defined by a string.+ Allows to define and do `isinstance()` checks without importing 3rd party libraries++ Example:+ ```python+ df = pd.DataFrame(...)+ _isinstance_external(df, class_ref="pandas.DataFrame")+ ```+ """+ import_parts = class_ref.split(".")+ module_name = import_parts[0]++ if module_name not in sys.modules:+ return False++ module: ModuleType = sys.modules[module_name]+ target_class: Any = module+ for part in import_parts:+ target_class = getattr(target_class, part)++ return isinstance(obj, target_class)+++class HasKeysMethod(Protocol):+ def keys(self) -> Collection[Any]: ...+++class HasColumnsProperty(Protocol):+ @property+ def columns(self) -> Collection[Any]: ...+++def _key_options_from_ipython_method(obj: Any) -> list[str]:+ # convention for `_ipython_key_completions_` is to return a list of strings+ return [str(key) for key in obj._ipython_key_completions_()]+++def _key_options_via_keys_method(obj: HasKeysMethod) -> list[str]:+ return [str(key) for key in obj.keys()]+++# TODO refactor to customize the `CompletionOption.info` with `"columns"`+def _key_options_via_columns_method(obj: HasColumnsProperty) -> list[str]:+ return [str(col) for col in obj.columns]+++def _key_options_dispatcher(obj: Any) -> list[str]:+ """Tries to get key completion suggestions from `obj`+ based on its methods and type.++ Returns a list of strings to later create marimo `CompletionOption`+ """+ if getattr(obj, "_ipython_key_completions_", False):+ return _key_options_from_ipython_method(obj)+ elif isinstance(obj, Mapping):+ return _key_options_via_keys_method(obj)+ elif _isinstance_external(obj, class_ref="pandas.DataFrame"):+ return _key_options_via_columns_method(obj)+ elif _isinstance_external(obj, class_ref="polars.DataFrame"):+ return _key_options_via_columns_method(obj)++ LOGGER.debug(+ f"No matching handlers found to retrieve keys from type `{type(obj)}`"+ )+ return []+++def _get_key_options(+ script: jedi.Script, glbls: dict[str, Any]+) -> list[CompletionOption]:+ """Get completion values for trigger `["` or `['`. Values are meant to be+ passed to `.__getitem__()`++ This implementation assumes that marimo's `CompletionRequest.document`+ only includes current line, up to the completion trigger.+ """+ names = script.get_names(+ references=True, definitions=False, all_scopes=False+ )+ if not names:+ LOGGER.debug(+ f"Retrieved no `names` for completion request: `{script._code}`"+ )+ return []++ obj_name = names[-1].name+ obj = glbls.get(obj_name)+ if obj is None:+ LOGGER.debug(f"Failed to find `{obj_name=:}` in `glbls`")+ return []++ keys = _key_options_dispatcher(obj)+ # TODO currently unreliable for non-string keys, even if stringified+ # seems to be related to serialization issue if include `"(True, False)` (no closing quote)+ return [+ CompletionOption(name=key, type="property", completion_info="key")+ for key in keys+ ]+++def _maybe_get_key_options(+ request: CodeCompletionRequest,+ script: jedi.Script,+ glbls: dict[str, Any],+ glbls_lock: threading.RLock,+) -> list[CompletionOption]:+ """Call key completions methods if the request contains the trigger"""+ triggers = ('["', "['") # explicitly handle both quotation characters+ if request.document[-2:] not in triggers:+ return []++ # TODO ideally, we don't acquire the lock twice with `_get_completions_with_interpreter()` and `_maybe_get_key_options`+ # however, the two functions are applied on different triggers+ # also, this other function returns Jedi `Completion` while this returns native `CompletionOption`+ locked = False+ locked = glbls_lock.acquire(blocking=False)+ if locked:+ try:+ return _get_key_options(script, glbls)+ finally:+ glbls_lock.release()+ else:+ return []++def _get_completions(codes: list[str],document: str,@@ -359,6 +489,9 @@ def _get_completions(return script, completions+# NOTE you will hit front display bug if the result set doesn't+# share the same `prefix_length`. This could happen if completion values+# are generated via different meansdef complete(request: CodeCompletionRequest,graph: dataflow.DirectedGraph,@@ -411,6 +544,24 @@ def complete(prefix_length: int = (completions[0].get_completion_prefix_length() if completions else 0)+ prefix = request.document[-prefix_length:]++ key_options = _maybe_get_key_options(+ request,+ script,+ glbls=glbls,+ glbls_lock=glbls_lock,+ )+ # if `key_options` are found, return early+ # we can return because key and attribute completions have non-overlapping triggers+ if key_options:+ _write_completion_result(+ stream=stream,+ completion_id=request.id,+ prefix_length=0, # values is static because of our implementation+ options=key_options,+ )+ returnif (prefix_length == 0@@ -448,7 +599,6 @@ def complete(_write_no_completions(stream, request.id)return- prefix = request.document[-prefix_length:]if timeout is None and isinstance(script, jedi.Interpreter):# We're holding the globals lock; set a short timeout so we don't# block the kerneldiff --git a/tests/_runtime/test_complete.py b/tests/_runtime/test_complete.pyindex f57eb39570..c7d7fd3571 100644--- a/tests/_runtime/test_complete.py+++ b/tests/_runtime/test_complete.py@@ -1,19 +1,32 @@from __future__ import annotations+import random+import threading+from collections.abc import Mappingfrom inspect import signaturefrom types import ModuleTypefrom typing import Any+from unittest import mockimport jediimport pytestimport marimofrom marimo._dependencies.dependencies import DependencyManager-from marimo._runtime.complete import _build_docstring_cached+from marimo._messaging.ops import CompletionResult+from marimo._messaging.types import Stream+from marimo._runtime.complete import (+ _build_docstring_cached,+ _maybe_get_key_options,+ complete,+)from marimo._runtime.patches import patch_jedi_parameter_completion+from marimo._runtime.requests import CodeCompletionRequest+from marimo._types.ids import CellId_tfrom tests.mocks import snapshottersnapshot = snapshotter(__file__)+HAS_PANDAS = DependencyManager.pandas.has()def test_build_docstring_function_no_init():@@ -205,3 +218,280 @@ def test_parameter_descriptions(obj: Any, runtime_inference: bool):assert "NoneType" not in docstring, (f"NoneType found in docstring: {call}{param_name}")+++def cases_key_completions_code() -> tuple[tuple[str, bool], ...]:+ """Text content when key completion is triggered."""+ return (+ ("obj['", True),+ ('obj["', True),+ ("assigned = obj['", True),+ ("multiline = 'foo'\nobj['", True),+ ("for i in iterator:\n\tobj['", True),+ # shouldn't trigger on the following notations+ ("obj.", False),+ ("obj", False),+ )+++def cases_objects_supporting_key_completion() -> tuple[+ tuple[Any, list[str]], ...+]:+ """Values stored in `globals` when key completion is triggered."""++ class IPythonImplemented:+ def __init__(self):+ self._table = {+ "foo": [0, 1],+ "bar": [1.0, 3.0],+ }++ @property+ def a_property(self) -> str:+ """This is a property"""+ return "prop value"++ def __getitem__(self, key: str) -> list:+ """Returns a mock column"""+ return self._table[key]++ def _ipython_key_completions_(self) -> list[str]:+ return list(self._table.keys())++ class CustomMapping(Mapping):+ def __init__(self):+ self._data = {+ "foo": [0, 1],+ "bar": [1.0, 3.0],+ }++ def __iter__(self):+ return iter(self._data.keys())++ def __getitem__(self, key):+ raise NotImplementedError++ def __len__(self):+ raise NotImplementedError++ static_key_dict = ({"foo": [0, 1], "bar": [1.0, 3.0]}, ["foo", "bar"])+ # use different ranges to prevent key collisions+ dynamic_key_1 = str(random.randint(0, 9))+ dynamic_key_2 = str(random.randint(10, 19))+ dynamic_key_dict = (+ {dynamic_key_1: "val1", dynamic_key_2: "val2"},+ [dynamic_key_1, dynamic_key_2],+ )+ mixed_keys_dict = (+ {"foo": [0, 1], dynamic_key_1: "val2"},+ ["foo", dynamic_key_1],+ )+ ipython_case = (IPythonImplemented(), ["foo", "bar"])+ custom_mapping_case = (CustomMapping(), ["foo", "bar"])++ return (+ static_key_dict,+ dynamic_key_dict,+ mixed_keys_dict,+ ipython_case,+ custom_mapping_case,+ )+++ "code_and_expects_completions", cases_key_completions_code()+)+ "obj_and_expected_completions", cases_objects_supporting_key_completion()+)+def test_maybe_get_key_options(+ code_and_expects_completions: tuple[str, bool],+ obj_and_expected_completions: tuple[Any, list[str]],+):+ """Low-level test for `_maybe_get_key_options()`"""+ code, expects_completions = code_and_expects_completions+ obj, expected_completions = obj_and_expected_completions++ glbls = {"obj": obj, "other": 10}+ lock = threading.RLock()+ script = jedi.Script(code=code)+ mock_request = mock.MagicMock()+ mock_request.document = code++ completions = _maybe_get_key_options(+ request=mock_request, script=script, glbls=glbls, glbls_lock=lock+ )++ if expects_completions is True:+ assert [c.name for c in completions] == expected_completions+ else:+ assert completions == []+++# TODO case could be added to `cases_objects_supporting_key_completions()`+# the test has the same logic of `test_maybe_get_key_options()`[email protected](not HAS_PANDAS, reason="pandas not installed.")+ "code_and_expects_completions", cases_key_completions_code()+)+def test_maybe_get_key_options_pandas_dataframe(+ code_and_expects_completions: tuple[str, bool],+):+ import pandas as pd++ glbls = {+ "obj": pd.DataFrame({"foo": [0, 1], "bar": [9.0, 2.0]}),+ "other": 10,+ }+ lock = threading.RLock()+ code, expects_completions = code_and_expects_completions+ expected_completions = ["foo", "bar"]+ mock_request = mock.MagicMock()+ mock_request.document = code++ script = jedi.Script(code=code)+ completions = _maybe_get_key_options(+ request=mock_request,+ script=script,+ glbls=glbls,+ glbls_lock=lock,+ )++ if expects_completions is True:+ assert [c.name for c in completions] == expected_completions+ else:+ assert completions == []+++class CaptureStream(Stream):+ def __init__(self):+ self.messages: list[tuple[str, dict[Any, Any]]] = []++ def write(self, op: str, data: dict[Any, Any]) -> None:+ self.messages.append((op, data))+++# TODO add test cases for all other completion modalities+# TODO improve coupling between variable name, source code, and assertions+ "code_and_expects_completions", cases_key_completions_code()+)+ "object_name", ["static_key", "dynamic_key", "mixed_keys", "ipython_data"]+)+def test_complete_main_entrypoint(+ code_and_expects_completions: tuple[str, bool],+ object_name: str,+) -> None:+ trigger_code, expects_completions = code_and_expects_completions++ # parameterize the test (object type, trigger code)+ # `trigger_code` includes different ways to trigger autocompletion (or not)+ # All `trigger_code` cases trigger completion on variable `obj`+ # To test different object types, we assign different values to `obj`+ other_cells_code = f'''\+import random++class CustomData:+ def __init__(self):+ self._table = {{+ "foo": [0, 1],+ "bar": [1., 3.],+ "baz": [True, True],+ }}++ @property+ def a_property(self) -> str:+ """This is a property"""+ return "prop value"++ def __getitem__(self, key: str) -> list:+ """Returns a mock column"""+ return self._table[key]++ def _ipython_key_completions_(self) -> list[str]:+ return list(self._table.keys())++ipython_data = CustomData()+static_key = {{"static_key": "foo"}}+dynamic_key = {{str(random.randint(0, 10)): "foo"}}+mixed_keys = {{"static_key": "foo", str(random.randint(0, 10)): "bar"}}+obj = {object_name}\+'''+ mock_other_cell = mock.MagicMock()+ mock_other_cell.code = other_cells_code++ mock_current_cell = mock.MagicMock()+ mock_current_cell.code = trigger_code+ current_cell_id = CellId_t("my-request-id")++ mock_graph = mock.MagicMock()+ mock_graph.cells = {+ "other-cell-id": mock_other_cell,+ current_cell_id: mock_current_cell,+ }++ glbls = {}+ exec(other_cells_code, {}, glbls)+ # check existence of variables in globals and their type+ assert isinstance(+ glbls.get("ipython_data"), glbls.get("CustomData", Exception)+ )+ assert isinstance(glbls.get("static_key"), dict)+ assert isinstance(glbls.get("dynamic_key"), dict)+ assert isinstance(glbls.get("mixed_keys"), dict)++ lock = threading.RLock()+ local_stream = CaptureStream()++ completion_request = CodeCompletionRequest(+ id="request_id",+ document=trigger_code,+ cell_id=current_cell_id,+ )++ complete(+ request=completion_request,+ graph=mock_graph,+ glbls=glbls,+ glbls_lock=lock,+ stream=local_stream,+ )++ messages = local_stream.messages+ message_name, content = messages[0]+ prefix_length = content["prefix_length"]+ options = content["options"]+ options_values = [option["name"] for option in options]++ assert len(messages) == 1+ assert message_name == CompletionResult.name+ # TODO if `expects_completions=False`, something else than `_maybe_get_key_options()`+ # could be returning values+ if expects_completions is False:+ return++ assert prefix_length == 0+ assert all(option["type"] == "property" for option in options)+ assert all(option["completion_info"] == "key" for option in options)++ expected_keys: list[str]+ if object_name == "static_key":+ # from source code in variable `other_cells_code`+ expected_keys = ["static_key"]+ elif object_name == "dynamic_key":+ expected_keys = list(glbls["dynamic_key"].keys())+ elif object_name == "mixed_keys":+ expected_keys = list(glbls["mixed_keys"].keys())+ elif object_name == "ipython_data":+ # from source code in variable `other_cells_code`+ expected_keys = ["foo", "bar", "baz"]+ else:+ RuntimeError(+ f"Make sure you defined `expected_keys` for `{object_name}`"+ " Currently, the test is improperly defined."+ )++ # check `len()` to ensure `set()` operation doesn't deduplicate keys+ assert len(options_values) == len(expected_keys)+ assert set(options_values) == set(expected_keys)