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
improvement: documentation of parameters as show in the completion box (#4673)
Michał Krassowskiaf222b1f2920
diff --git a/frontend/src/core/codemirror/language/python.ts b/frontend/src/core/codemirror/language/python.tsindex 9f24555d12..8f64ded8a2 100644--- a/frontend/src/core/codemirror/language/python.ts+++ b/frontend/src/core/codemirror/language/python.ts@@ -78,7 +78,12 @@ const lspClient = once((lspConfig: LSPConfig) => {enabled: true,},jedi: {- auto_import_modules: ["marimo", "numpy"],+ // Modules which should be imported and use compile-time, rather+ // than static analysis; this is a trade-off between being able+ // to access more information set on runtime (e.g. via setattr)+ // vs being able to read the information from the source code+ // (e.g. comments with documentation for attributes).+ auto_import_modules: ["numpy"],},jedi_completion: {// Ensure that parameters are included for completion snippets.diff --git a/marimo/_ai/_types.py b/marimo/_ai/_types.pyindex f977141266..9a104b195e 100644--- a/marimo/_ai/_types.py+++ b/marimo/_ai/_types.py@@ -68,11 +68,22 @@ class ChatMessage:@dataclassclass ChatModelConfig:+ # Maximum number of tokens.max_tokens: Optional[int] = None++ # Temperature for the model (randomness).temperature: Optional[float] = None++ # Restriction on the cumulative probability of prediction candidates.top_p: Optional[float] = None++ # Number of top prediction candidates to consider.top_k: Optional[int] = None++ # Penalty for tokens which appear frequently.frequency_penalty: Optional[float] = None++ # Penalty for tokens which already appeared at least once.presence_penalty: Optional[float] = Nonediff --git a/marimo/_ai/llm/_impl.py b/marimo/_ai/llm/_impl.pyindex b7a51dd337..33327e105a 100644--- a/marimo/_ai/llm/_impl.py+++ b/marimo/_ai/llm/_impl.py@@ -27,10 +27,9 @@ class simple(ChatModel):Convenience class for wrapping a ChatModel or callable totake a single prompt- **Args:**-- - delegate: A callable that takes a- single prompt and returns a response+ Args:+ delegate: A callable that takes a+ single prompt and returns a response"""def __init__(self, delegate: Callable[[str], object]):@@ -48,15 +47,14 @@ class openai(ChatModel):"""OpenAI ChatModel- **Args:**-- - model: The model to use.- Can be found on the [OpenAI models page](https://platform.openai.com/docs/models)- - system_message: The system message to use- - api_key: The API key to use.- If not provided, the API key will be retrieved- from the OPENAI_API_KEY environment variable or the user's config.- - base_url: The base URL to use+ Args:+ model: The model to use.+ Can be found on the [OpenAI models page](https://platform.openai.com/docs/models)+ system_message: The system message to use+ api_key: The API key to use.+ If not provided, the API key will be retrieved+ from the OPENAI_API_KEY environment variable or the user's config.+ base_url: The base URL to use"""def __init__(@@ -160,16 +158,15 @@ class anthropic(ChatModel):"""Anthropic ChatModel- **Args:**-- - model: The model to use.- Can be found on the [Anthropic models page](https://docs.anthropic.com/en/docs/about-claude/models)- - system_message: The system message to use- - api_key: The API key to use.- If not provided, the API key will be retrieved- from the ANTHROPIC_API_KEY environment variable- or the user's config.- - base_url: The base URL to use+ Args:+ model: The model to use.+ Can be found on the [Anthropic models page](https://docs.anthropic.com/en/docs/about-claude/models)+ system_message: The system message to use+ api_key: The API key to use.+ If not provided, the API key will be retrieved+ from the ANTHROPIC_API_KEY environment variable+ or the user's config.+ base_url: The base URL to use"""def __init__(@@ -258,15 +255,14 @@ class google(ChatModel):"""Google AI ChatModel- **Args:**-- - model: The model to use.- Can be found on the [Gemini models page](https://ai.google.dev/gemini-api/docs/models/gemini)- - system_message: The system message to use- - api_key: The API key to use.- If not provided, the API key will be retrieved- from the GOOGLE_AI_API_KEY environment variable- or the user's config.+ Args:+ model: The model to use.+ Can be found on the [Gemini models page](https://ai.google.dev/gemini-api/docs/models/gemini)+ system_message: The system message to use+ api_key: The API key to use.+ If not provided, the API key will be retrieved+ from the GOOGLE_AI_API_KEY environment variable+ or the user's config."""def __init__(@@ -338,15 +334,14 @@ class groq(ChatModel):"""Groq ChatModel- **Args:**-- - model: The model to use.- Can be found on the [Groq models page](https://console.groq.com/docs/models)- - system_message: The system message to use- - api_key: The API key to use.- If not provided, the API key will be retrieved- from the GROQ_API_KEY environment variable or the user's config.- - base_url: The base URL to use+ Args:+ model: The model to use.+ Can be found on the [Groq models page](https://console.groq.com/docs/models)+ system_message: The system message to use+ api_key: The API key to use.+ If not provided, the API key will be retrieved+ from the GROQ_API_KEY environment variable or the user's config.+ base_url: The base URL to use"""def __init__(diff --git a/marimo/_islands/_island_generator.py b/marimo/_islands/_island_generator.pyindex 505ef4e714..3b012bdb95 100644--- a/marimo/_islands/_island_generator.py+++ b/marimo/_islands/_island_generator.py@@ -29,6 +29,17 @@ LOGGER = _loggers.marimo_logger()class MarimoIslandStub:+ """+ Args:+ display_code: Whether to display code.+ display_output: Whether to display output.+ is_reactive: Whether it is reactive.+ cell_id: Cell identifier.+ app_id: App identifier.+ app_id: App identifier.+ code: Code.+ """+def __init__(self,display_code: bool = False,@@ -173,8 +184,7 @@ class MarimoIslandGenerator:3. Replace all code snippets with the rendered HTML.4. Include the header in the <head> tag.- # Example-+ Examples:Using the MarimoIslandGenerator class:```pythonimport asyncio@@ -231,6 +241,8 @@ class MarimoIslandGenerator:f.write(html)```+ Args:+ app_id: The optional identifier of the app, defaults to `main`."""def __init__(self, app_id: str = "main"):diff --git a/marimo/_output/data/data.py b/marimo/_output/data/data.pyindex f54d82835e..08b3df1caa 100644--- a/marimo/_output/data/data.py+++ b/marimo/_output/data/data.py@@ -85,13 +85,11 @@ def arrow(data: bytes) -> VirtualFile:def parquet(data: bytes) -> VirtualFile:"""Create a virtual file for Parquet data.- **Args.**-- - data: Parquet data in bytes-- **Returns.**+ Args:+ data: Parquet data in bytes- A `VirtualFile` object.+ Returns:+ A `VirtualFile` object."""return any_data(data, ext="parquet") # type: ignorediff --git a/marimo/_output/justify.py b/marimo/_output/justify.pyindex f56170e59d..96d65b4812 100644--- a/marimo/_output/justify.py+++ b/marimo/_output/justify.py@@ -8,6 +8,9 @@ from marimo._output.rich_help import mddocdef center(item: object) -> Html:"""Center an item.+ Args:+ item: object to center.+Returns:A centered `Html` object."""@@ -18,6 +21,9 @@ def center(item: object) -> Html:def left(item: object) -> Html:"""Left-justify an item.+ Args:+ item: object to left-justify.+Returns:A left-justified `Html` object."""@@ -28,6 +34,9 @@ def left(item: object) -> Html:def right(item: object) -> Html:"""Right-justify an item.+ Args:+ item: object to right-justify.+Returns:A right-justified `Html` object."""diff --git a/marimo/_output/md.py b/marimo/_output/md.pyindex c4842155b2..7316e950c0 100644--- a/marimo/_output/md.py+++ b/marimo/_output/md.py@@ -209,13 +209,11 @@ def md(text: str) -> Html:$$- **Args**:+ Args:+ text: a string of markdown- - `text`: a string of markdown-- **Returns**:-- - An `Html` object.+ Returns:+ An `Html` object."""return _md(text)@@ -237,11 +235,11 @@ def latex(*, filename: Union[str, Path]) -> None:mo.latex(filename="https://example.com/macros.tex")```- **Args**:- - `filename`: Path to a LaTeX file+ Args:+ filename: Path to a LaTeX file- **Returns**:- - An `Html` object+ Returns:+ An `Html` object"""if isinstance(filename, Path):diff --git a/marimo/_output/show_code.py b/marimo/_output/show_code.pyindex 4909956109..36d3f6c432 100644--- a/marimo/_output/show_code.py+++ b/marimo/_output/show_code.py@@ -69,17 +69,15 @@ def show_code(mo.show_code()```- **Args:**-- - `output`: the output to display with the cell's code; omit the output- to just show the cell's code.- - `position`: Where to display the code relative to the output.- Use "above" to show code above the output, or "below" (default) to show- code below the output.-- **Returns:**-- HTML of the `output` arg displayed with its code.+ Args:+ output: the output to display with the cell's code; omit the output+ to just show the cell's code.+ position: Where to display the code relative to the output.+ Use "above" to show code above the output, or "below" (default) to show+ code below the output.++ Returns:+ HTML of the `output` arg displayed with its code."""assert position in ["above", "below"], ("position must be 'above' or 'below'"diff --git a/marimo/_plugins/ui/_impl/data_editor.py b/marimo/_plugins/ui/_impl/data_editor.pyindex fa03e83b4f..307c8125c7 100644--- a/marimo/_plugins/ui/_impl/data_editor.py+++ b/marimo/_plugins/ui/_impl/data_editor.py@@ -135,6 +135,8 @@ class data_editor(on_change (Optional[Callable]): Optional callback to run when this element's value changes.column_sizing_mode (Literal["auto", "fit"]): The column sizing mode for the table.`auto` will size columns based on the content, `fit` will size columns to fit the view.+ pagination (Optional[bool]): Whether to use pagination, enabled by default.+ page_size (Optional[int]): Page size if pagination is in use, 50 by default."""_name: Final[str] = "marimo-data-editor"diff --git a/marimo/_plugins/ui/_impl/data_explorer.py b/marimo/_plugins/ui/_impl/data_explorer.pyindex 0c9244b0e4..fd510543f3 100644--- a/marimo/_plugins/ui/_impl/data_explorer.py+++ b/marimo/_plugins/ui/_impl/data_explorer.py@@ -27,6 +27,8 @@ class data_explorer(UIElement[dict[str, Any], dict[str, Any]]):Args:df (IntoDataFrame): The DataFrame to visualize.+ on_change (Callable[[dict[str, object]], None], optional): Optional callback+ to run when this element's value changes."""_name: Final[str] = "marimo-data-explorer"diff --git a/marimo/_plugins/ui/_impl/dictionary.py b/marimo/_plugins/ui/_impl/dictionary.pyindex df1e9968c6..974ef9f178 100644--- a/marimo/_plugins/ui/_impl/dictionary.py+++ b/marimo/_plugins/ui/_impl/dictionary.py@@ -91,6 +91,8 @@ class dictionary(_batch_base):elements (dict[str, UIElement[Any, Any]]): A dict mapping names to UIelements to include.label (str, optional): A descriptive name for the dictionary. Defaults to "".+ on_change (Callable[[dict[str, object]], None], optional): Optional callback+ to run when this element's value changes."""def __init__(diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex 5e2d24412f..c118979d0a 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -279,7 +279,7 @@ class table(selection (Literal["single", "multi", "single-cell", "multi-cell"], optional): 'single' or 'multi' to enable row selection,'single-cell' or 'multi-cell' to enable cell selectionor None to disable. Defaults to "multi".- initial_selection (Union[List[int], List[tuple[str, str]), optional): Indices of the rows you want selected by default.+ initial_selection (Union[List[int], List[tuple[str, str]], optional): Indices of the rows you want selected by default.page_size (int, optional): The number of rows to show per page. Defaults to 10.show_column_summaries (Union[bool, Literal["stats", "chart"]], optional): Whether to show column summaries.Defaults to True when the table has less than 40 columns and at least 10 rows, False otherwise.@@ -299,6 +299,7 @@ class table(style_cell (Callable[[str, str, Any], Dict[str, Any]], optional): A function that takes the row id, column name and value and returns a dictionary of CSS styles.max_columns (int, optional): Maximum number of columns to display. Defaults to 50.Set to None to show all columns.+ label (str, optional): A descriptive name for the table. Defaults to ""."""_name: Final[str] = "marimo-table"diff --git a/marimo/_plugins/ui/_impl/tabs.py b/marimo/_plugins/ui/_impl/tabs.pyindex ef8b5c9ac8..ea5bd2bea5 100644--- a/marimo/_plugins/ui/_impl/tabs.py+++ b/marimo/_plugins/ui/_impl/tabs.py@@ -48,6 +48,9 @@ class tabs(UIElement[str, str]):lazy (bool, optional): Whether to lazily load the tab content.This is a convenience that wraps each tab in a `mo.lazy`component. Defaults to False.+ label (str, optional): A descriptive name for the tab. Defaults to "".+ on_change (Callable[[dict[str, object]], None], optional): Optional callback+ to run when this element's value changes."""_name: Final[str] = "marimo-tabs"diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.pyindex bb9468aa47..726e6ea223 100644--- a/marimo/_runtime/complete.py+++ b/marimo/_runtime/complete.py@@ -495,13 +495,12 @@ def completion_worker("""Code completion worker.- **Args:**-- - `completion_queue`: queue from which requests are pulled.- - `graph`: dataflow graph backing the marimo program- - `glbls`: dictionary of global variables in interpreter memory- - `glbls_lock`: lock protecting globals- - `stream`: stream used to communicate completion results+ Args:+ completion_queue: queue from which requests are pulled.+ graph: dataflow graph backing the marimo program+ glbls: dictionary of global variables in interpreter memory+ glbls_lock: lock protecting globals+ stream: stream used to communicate completion results"""while True:diff --git a/marimo/_runtime/control_flow.py b/marimo/_runtime/control_flow.pyindex 843fd64063..8c4fa20f26 100644--- a/marimo/_runtime/control_flow.py+++ b/marimo/_runtime/control_flow.py@@ -16,6 +16,9 @@ class MarimoStopError(BaseException):Inherits from `BaseException` to prevent accidental capture with`except Exception` (similar to `KeyboardInterrupt`)++ Args:+ output: optional output object"""def __init__(self, output: Optional[object]) -> None:@@ -37,6 +40,10 @@ def stop(predicate: bool, output: Optional[object] = None) -> None:mo.stop(form.value is None, mo.md("**Submit the form to continue.**"))```+ Args:+ predicate (bool): The predicate indicating whether to stop.+ output (bool): The output to be assigned to the current cell.+Raises:MarimoStopError: When `predicate` is `True`"""diff --git a/marimo/_runtime/output/_output.py b/marimo/_runtime/output/_output.pyindex 7c2d38e826..15773a1286 100644--- a/marimo/_runtime/output/_output.py+++ b/marimo/_runtime/output/_output.py@@ -32,9 +32,8 @@ def replace(value: object) -> None:Call `mo.output.replace()` to write to a cell's output area, replacingthe existing output, if any.- **Args:**-- - `value`: object to output+ Args:+ value: object to output"""try:ctx = get_context()@@ -57,10 +56,9 @@ def replace_at_index(value: object, idx: int) -> None:Call this function to replace an existing object in a cell's output. If idxis equal to the length of the output, this is equivalent to an append.- **Args:**-- - `value`: new object to replace an existing object- - `idx`: index of output to replace+ Args:+ value: new object to replace an existing object+ idx: index of output to replace"""try:@@ -91,9 +89,8 @@ def append(value: object) -> None:Call this function to incrementally build a cell's output. Appendedoutputs are stacked vertically.- **Args:**-- - `value`: object to output+ Args:+ value: object to output"""try:ctx = get_context()diff --git a/marimo/_runtime/params.py b/marimo/_runtime/params.pyindex 455e25b689..44bebde242 100644--- a/marimo/_runtime/params.py+++ b/marimo/_runtime/params.py@@ -117,7 +117,12 @@ class QueryParams(State[SerializedQueryParams]):self[key] = valuedef append(self, key: str, value: str) -> None:- """Append a value to a list of values"""+ """Append a value to a list of values++ Args:+ key: The key identifying the list; the list will be created if needed.+ value: The value to append.+ """if key not in self._params:self._params[key] = valueQueryParamsAppend(key, value).broadcast(self._stream)@@ -134,7 +139,12 @@ class QueryParams(State[SerializedQueryParams]):self._set_value(self._params)def remove(self, key: str, value: Optional[str] = None) -> None:- """Remove a value from a list of values."""+ """Remove a value from a list of values.++ Args:+ key: The key identifying the list; no-op if absent.+ value: The optional value to remove; if not given the entire list gets removed.+ """if key not in self._params:return# If value is None, remove the keydiff --git a/marimo/_runtime/patches.py b/marimo/_runtime/patches.pyindex a3049fb8f3..4cc093e4c5 100644--- a/marimo/_runtime/patches.py+++ b/marimo/_runtime/patches.py@@ -8,11 +8,17 @@ import textwrapimport typesfrom typing import TYPE_CHECKING, Any, Callable+from marimo._dependencies.dependencies import DependencyManagerfrom marimo._runtime import marimo_browser, marimo_pdbif TYPE_CHECKING:from collections.abc import Iterator+ from jedi.inference.base_value import ( # type: ignore[import-untyped]+ ValueSet,+ )+ from parso.python.tree import ExprStmt+def patch_pdb(debugger: marimo_pdb.MarimoPdb) -> None:import pdb@@ -207,3 +213,205 @@ def patch_main_module_context(yield modulefinally:sys.modules["__main__"] = main+++def patch_jedi_parameter_completion() -> None:+ import re++ from jedi.inference.compiled import ( # type: ignore[import-untyped]+ CompiledValue,+ )+ from jedi.inference.compiled.value import ( # type: ignore[import-untyped]+ SignatureParamName,+ )+ from jedi.inference.names import ( # type: ignore[import-untyped]+ AnonymousParamName,+ ParamNameWrapper,+ )+ from jedi.parser_utils import ( # type: ignore[import-untyped]+ clean_scope_docstring,+ )++ original_static_infer = AnonymousParamName.infer+ original_dynamic_infer = SignatureParamName.infer++ original_dynamic_init: Callable[..., None] = SignatureParamName.__init__++ def find_statement_documentation(tree_node: ExprStmt) -> str:+ """Find documentation of a statement (attribute in a class).++ By default jedi's `find_statement_documentation` will search+ for strings >below< attributes (not above); while that follows+ the convention of docstrings being below function signature,+ it is often contrary to what authors expect, which is comments+ above attributes in data classes.+ """+ if tree_node.type == "expr_stmt":+ maybe_name = tree_node.children[0]+ if maybe_name.type != "name":+ return ""+ maybe_comment = getattr(maybe_name, "prefix", None)+ if not isinstance(maybe_comment, str):+ return ""+ maybe_comment = maybe_comment.strip()+ if not maybe_comment.startswith("#"):+ return ""+ lines = [+ line.strip().lstrip("#") for line in maybe_comment.splitlines()+ ]+ min_indent = min(+ [len(line) - len(line.lstrip()) for line in lines]+ )+ return "\n".join(+ line.strip().lstrip("#")[min_indent:]+ for line in maybe_comment.splitlines()+ )+ return ""++ def extract_marimo_style_arguments(docstring: str) -> dict[str, str]:+ lines = docstring.splitlines()+ try:+ start = lines.index("# Arguments")+ except ValueError:+ return {}+ parsing_marimo_docstring = False+ param_descriptions: dict[str, str] = {}+ for line in lines[start + 1 :]:+ if line == "| Parameter | Type | Description |":+ parsing_marimo_docstring = True+ continue+ if line == "|-----------|------|-------------|":+ continue+ if parsing_marimo_docstring:+ if line.strip() == "" or line.startswith("#"):+ parsing_marimo_docstring = False+ continue+ match = re.match(+ r"^\| `(.+)` \| `(.*)` \| (.*) \|$", line.strip()+ )+ if match:+ param, _param_type, description = match.groups()+ param_descriptions[param] = description+ return param_descriptions++ def extract_docstring_to_markdown_arguments(+ docstring: str,+ ) -> dict[str, str]:+ param_descriptions: dict[str, str] = {}+ lines = docstring.splitlines()+ try:+ start = lines.index("#### Parameters")+ except ValueError:+ return {}+ param = None+ for line in lines[start + 2 :]:+ if line.strip() == "" or line.startswith("#"):+ continue+ param_start = re.match(r"^\- `(.+)`: (.*)$", line.strip())+ if param_start:+ param, first_line = param_start.groups()+ param_descriptions[param] = first_line+ else:+ if param:+ param_descriptions[param] += "\n" + line.strip()+ return param_descriptions++ def py__doc__(self: ParamNameWrapper) -> str:+ # Patch for https://github.com/davidhalter/jedi/issues/2061+ if self.tree_name is None:+ # This will only happen for runtime (imported packages)+ arg_name = self.string_name++ if self.parent_context.is_class():+ docstring = self.parent_context.py__doc__()+ else:+ docstring = self.compiled_value.py__doc__()+ else:+ # Static analysis+ definition = self.tree_name.get_definition()+ if definition.type not in {"param", "expr_stmt"}:+ return ""+ if definition.type == "expr_stmt":+ # The case of dataclasses.+ return find_statement_documentation(+ self.tree_name.get_definition()+ )+ arg_name = definition.name.value++ if self.parent_context.is_class():+ docstring = self.parent_context.py__doc__()+ else:+ docstring = clean_scope_docstring(definition.parent.parent)++ if DependencyManager.docstring_to_markdown.has():+ from docstring_to_markdown import ( # type: ignore[import-not-found]+ UnknownFormatError,+ convert,+ )++ try:+ docstring = convert(docstring)+ except UnknownFormatError:+ return ""++ if "# Arguments" in docstring:+ param_descriptions = extract_marimo_style_arguments(docstring)+ else:+ param_descriptions = extract_docstring_to_markdown_arguments(+ docstring+ )++ if arg_name in param_descriptions:+ return param_descriptions[arg_name]+ return ""++ def filter_none_value(value: Any) -> bool:+ if not isinstance(value, CompiledValue):+ return True+ value_repr: str = value.access_handle.get_repr()+ return not (+ value_repr == "None"+ or+ # numpy's special type acting as a sentinel+ # in new and deprecated keyword arguments+ "_NoValueType" in value_repr+ )++ def wrap_infer(+ original_infer: Callable[[Any], ValueSet],+ ) -> Callable[[Any], ValueSet]:+ def infer(self: AnonymousParamName | SignatureParamName) -> ValueSet:+ # Patch for https://github.com/davidhalter/jedi/issues/2063+ result = original_infer(self)+ return result.filter(filter_none_value)++ infer.patched = True # type: ignore[attr-defined]+ return infer++ py__doc__.patched = True # type: ignore[attr-defined]++ def enhanced_init(+ self: SignatureParamName,+ compiled_value: CompiledValue,+ signature_param: str,+ ) -> None:+ original_dynamic_init(self, compiled_value, signature_param)+ self.compiled_value = compiled_value++ enhanced_init.patched = True # type: ignore[attr-defined]++ if not (+ hasattr(ParamNameWrapper, "py__doc__")+ and getattr(ParamNameWrapper.py__doc__, "patched", False)+ ):+ ParamNameWrapper.py__doc__ = py__doc__+ if not (+ hasattr(AnonymousParamName, "infer")+ and getattr(AnonymousParamName.infer, "patched", False)+ ):+ AnonymousParamName.infer = wrap_infer(original_static_infer)++ if not getattr(SignatureParamName.infer, "patched", False):+ SignatureParamName.infer = wrap_infer(original_dynamic_infer)+ if not getattr(SignatureParamName.__init__, "patched", False):+ SignatureParamName.__init__ = enhanced_initdiff --git a/marimo/_save/save.py b/marimo/_save/save.pyindex 0536cf97fd..9845f326da 100644--- a/marimo/_save/save.py+++ b/marimo/_save/save.py@@ -503,8 +503,7 @@ def cache( # type: ignore[misc]Decorating a function with `@mo.cache` will cache its value based onthe function's arguments, closed-over values, and the notebook code.- **Usage.**-+ Examples:```pythonimport marimo as mo@@ -540,10 +539,9 @@ def cache( # type: ignore[misc]Note, `mo.cache` can also be used as a drop in replacement for context blockcaching like `mo.persistent_cache`.- **Args**:-- - `pin_modules`: if True, the cache will be invalidated if module versions- differ.+ Args:+ pin_modules: if True, the cache will be invalidated if module versions+ differ.## Context manager to cache the return value of a block of code.@@ -553,20 +551,20 @@ def cache( # type: ignore[misc]By default, the cache is stored in memory and is not persisted across kernelruns, for that functionality, refer to `mo.persistent_cache`.- **Usage.**-+ Examples:```pythonwith mo.cache("my_cache") as cache:variable = expensive_function()```- **Args**:-- - `name`: the name of the cache, used to set saving path- to manually- invalidate the cache, change the name.- - `pin_modules`: if True, the cache will be invalidated if module versions- differ.- - `loader`: the loader to use for the cache, defaults to `MemoryLoader`.+ Args:+ name: the name of the cache, used to set saving path- to manually+ invalidate the cache, change the name.+ pin_modules: if True, the cache will be invalidated if module versions+ differ.+ loader: the loader to use for the cache, defaults to `MemoryLoader`.+ **kwargs: keyword arguments+ *args: positional arguments"""arg = namedel name@@ -613,8 +611,7 @@ def lru_cache( # type: ignore[misc]retained, with the oldest values being discarded. For more information,see the documentation of `mo.cache`.- **Usage.**-+ Examples:```pythonimport marimo as mo@@ -624,22 +621,22 @@ def lru_cache( # type: ignore[misc]return n * factorial(n - 1) if n else 1```- **Args**:-- - `maxsize`: the maximum number of entries in the cache; defaults to 128.- Setting to -1 disables cache limits.- - `pin_modules`: if True, the cache will be invalidated if module versions- differ.+ Args:+ maxsize: the maximum number of entries in the cache; defaults to 128.+ Setting to -1 disables cache limits.+ pin_modules: if True, the cache will be invalidated if module versions+ differ.## Context manager for LRU caching the return value of a block of code.- **Args**:-- - `name`: Namespace key for the cache.- - `maxsize`: the maximum number of entries in the cache; defaults to 128.- Setting to -1 disables cache limits.- - `pin_modules`: if True, the cache will be invalidated if module versions- differ.+ Args:+ name: Namespace key for the cache.+ maxsize: the maximum number of entries in the cache; defaults to 128.+ Setting to -1 disables cache limits.+ pin_modules: if True, the cache will be invalidated if module versions+ differ.+ **kwargs: keyword arguments passed to `cache()`+ *args: positional arguments passed to `cache()`"""arg = namedel name@@ -703,8 +700,7 @@ def persistent_cache( # type: ignore[misc]that would otherwise be expensive to compute already materialized inmemory.- **Usage.**-+ Examples:```pythonwith persistent_cache(name="my_cache"):variable = expensive_function() # This will be cached to disk.@@ -723,16 +719,18 @@ def persistent_cache( # type: ignore[misc]**Warning.** Since context abuses sys frame trace, this may conflict withdebugging tools or libraries that also use `sys.settrace`.- **Args**:-- - `name`: the name of the cache, used to set saving path- to manually- invalidate the cache, change the name.- - `save_path`: the folder in which to save the cache, defaults to- `__marimo__/cache` in the directory of the notebook file- - `method`: the serialization method to use, current options are "json",- and "pickle" (default).- - `pin_modules`: if True, the cache will be invalidated if module versions- differ between runs, defaults to False.+ Args:+ name: the name of the cache, used to set saving path- to manually+ invalidate the cache, change the name.+ save_path: the folder in which to save the cache, defaults to+ `__marimo__/cache` in the directory of the notebook file+ method: the serialization method to use, current options are "json",+ and "pickle" (default).+ pin_modules: if True, the cache will be invalidated if module versions+ differ between runs, defaults to False.+ store: optional store.+ **kwargs: keyword arguments passed to `cache()`+ *args: positional arguments passed to `cache()`## Decorator for persistently caching the return value of a function.@@ -759,15 +757,14 @@ def persistent_cache( # type: ignore[misc]# Do expensive things```- **Args**:-- - `fn`: the wrapped function if no settings are passed.- - `save_path`: the folder in which to save the cache, defaults to- `__marimo__/cache` in the directory of the notebook file- - `method`: the serialization method to use, current options are "json",- and "pickle" (default).- - `pin_modules`: if True, the cache will be invalidated if module versions- differ between runs, defaults to False.+ Args:+ fn: the wrapped function if no settings are passed.+ save_path: the folder in which to save the cache, defaults to+ `__marimo__/cache` in the directory of the notebook file+ method: the serialization method to use, current options are "json",+ and "pickle" (default).+ pin_modules: if True, the cache will be invalidated if module versions+ differ between runs, defaults to False."""arg = namediff --git a/marimo/_utils/docs.py b/marimo/_utils/docs.pyindex 1e103df166..f48ae0d862 100644--- a/marimo/_utils/docs.py+++ b/marimo/_utils/docs.py@@ -4,6 +4,8 @@ from __future__ import annotationsimport refrom textwrap import dedent+from marimo._runtime.patches import patch_jedi_parameter_completion+def google_docstring_to_markdown(docstring: str) -> str:"""@@ -201,6 +203,9 @@ def google_docstring_to_markdown(docstring: str) -> str:class MarimoConverter:priority = 100+ def __init__(self) -> None:+ patch_jedi_parameter_completion()+SECTION_HEADERS = ["Args", "Returns", "Raises", "Examples"]def convert(self, docstring: str) -> str:diff --git a/tests/_runtime/test_complete.py b/tests/_runtime/test_complete.pyindex 3a43d86c8a..b11b247a7a 100644--- a/tests/_runtime/test_complete.py+++ b/tests/_runtime/test_complete.py@@ -1,7 +1,15 @@from __future__ import annotations+from inspect import signature+from types import ModuleType++import jedi+import pytest++import marimofrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._runtime.complete import _build_docstring_cached+from marimo._runtime.patches import patch_jedi_parameter_completionfrom tests.mocks import snapshottersnapshot = snapshotter(__file__)@@ -94,3 +102,90 @@ def test_build_docstring_no_signature_no_body():init_docstring=None,)assert len(result.strip()) == 0+++def collect_modules_to_check():+ top_level_modules_to_check = [marimo]+ submodules_to_check = []++ # Collect all public exported sub-modules+ for module in top_level_modules_to_check:+ for attribute in dir(module):+ if attribute.startswith("_"):+ continue+ candidate = getattr(module, attribute)+ if isinstance(candidate, ModuleType):+ submodules_to_check.append(candidate)++ return top_level_modules_to_check + submodules_to_check+++def collect_functions_to_check():+ modules_to_check = collect_modules_to_check()+ assert len(modules_to_check) > 1+ objects_to_check = set()+ for module in modules_to_check:+ for attribute in dir(module):+ if attribute.startswith("_"):+ continue+ obj = getattr(module, attribute)+ if not callable(obj):+ continue+ objects_to_check.add(obj)+ assert len(objects_to_check) > 1+ return objects_to_check+++ not DependencyManager.docstring_to_markdown.has(),+ reason="docstring_to_markdown is not installed",+)+ ("obj", "runtime_inference"),+ [[obj, False] for obj in collect_functions_to_check()]+ + [+ # Test runtime inference for a subset of values+ [marimo.accordion, True]+ ],+ ids=lambda obj: f"{obj}"+ if isinstance(obj, bool)+ else f"{obj.__module__}.{obj.__qualname__}",+)+def test_parameter_descriptions(obj, runtime_inference):+ patch_jedi_parameter_completion()+ import_name = obj.__module__+ marimo_export = obj.__name__+ path = f"{import_name}.{marimo_export}"+ if path == "marimo._output.hypertext.Html":+ pytest.skip("Known issue with `Html` being a quasi-dataclass")+ if path.startswith("marimo._save.save."):+ pytest.skip(+ "Cache functions use overloads to distinguish calls and context managers"+ " this can be fixed by splitting docstring on per-oveload basis, but that"+ " is not yet supported by mkdocstrings for documentation rendering, see"+ " https://github.com/mkdocstrings/python/issues/135"+ )+ call = f"{path}("+ code = f"import {import_name};{call}"+ jedi.settings.auto_import_modules = ["marimo"] if runtime_inference else []+ script = jedi.Script(code=code)+ completions = script.complete(line=1, column=len(code))+ param_completions = {+ completion.name[:-1]: completion+ for completion in completions+ if completion.name.endswith("=")+ }+ for param_name, param in signature(obj).parameters.items():+ if param_name.startswith("_"):+ continue+ if param.kind in {param.VAR_KEYWORD, param.VAR_POSITIONAL}:+ continue+ assert param_name in param_completions, (+ f"Jedi did not suggest {param_name} in {call}"+ )+ jedi_param = param_completions[param_name]+ docstring = jedi_param.docstring()+ assert docstring != "", f"Empty docstring result: {call}{param_name}"+ assert "NoneType" not in docstring, (+ f"NoneType found in docstring: {call}{param_name}"+ )