Skip to content

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.

improvement: support google style docs in our completion (#3211)

Myles Scolnickc08e06bb6a6c
diff --git a/frontend/src/components/editor/documentation.css b/frontend/src/components/editor/documentation.css
index 63264e26e5..39bc24e460 100644
--- a/frontend/src/components/editor/documentation.css
+++ b/frontend/src/components/editor/documentation.css
@@ -53,7 +53,7 @@
}
code {
- @apply border px-1 rounded font-mono bg-[var(--slate-1)] text-sm;
+ @apply border px-1 rounded font-mono bg-[var(--slate-1)] text-sm mb-4 mt-2;
}
h1 {
diff --git a/marimo/_plugins/ui/_impl/from_panel.py b/marimo/_plugins/ui/_impl/from_panel.py
index 660fd1cc9e..ea44c3a4ff 100644
--- a/marimo/_plugins/ui/_impl/from_panel.py
+++ b/marimo/_plugins/ui/_impl/from_panel.py
@@ -250,9 +250,9 @@ class panel(UIElement[T, T]):
def _handle_msg(self, msg: SendToWidgetArgs) -> None:
ref = self._ref
- comm = self.obj._comms[ref][0]
+ comm = self.obj._comms[ref][0] # type: ignore[attr-defined]
msg = comm.decode(msg)
- self.obj._on_msg(ref, self._manager, msg)
+ self.obj._on_msg(ref, self._manager, msg) # type: ignore[attr-defined]
comm.send(data={"type": "ACK"})
def _initialize(
@@ -260,7 +260,7 @@ class panel(UIElement[T, T]):
initialization_args: InitializationArgs[T, T],
) -> None:
super()._initialize(initialization_args)
- for comm, _ in self.obj._comms.values():
+ for comm, _ in self.obj._comms.values(): # type: ignore[attr-defined]
if isinstance(comm.comm, MarimoComm):
comm.comm.ui_element_id = self._id
diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.py
index afc53a82d2..207209a9b9 100644
--- a/marimo/_runtime/complete.py
+++ b/marimo/_runtime/complete.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import html
import threading
import time
+from functools import lru_cache
from typing import TYPE_CHECKING, Any, cast
import jedi # type: ignore # noqa: F401
@@ -17,6 +18,7 @@ from marimo._output.md import _md
from marimo._runtime import dataflow
from marimo._runtime.requests import CodeCompletionRequest
from marimo._server.types import QueueType
+from marimo._utils.docs import google_docstring_to_markdown
from marimo._utils.format_signature import format_signature
from marimo._utils.rst_to_html import convert_rst_to_html
@@ -52,94 +54,144 @@ def _should_include_name(name: str, prefix: str) -> bool:
return True
+DOC_CACHE_SIZE = 200
+
+
+@lru_cache(maxsize=DOC_CACHE_SIZE)
+def _build_docstring_cached(
+ completion_type: str,
+ completion_name: str,
+ module_name: str,
+ signature_strings: tuple[str, ...],
+ raw_body: str | None,
+ init_docstring: str | None,
+) -> str:
+ """Builds the docstring that includes signatures and body."""
+ if not signature_strings:
+ # handle modules, keywords, etc.
+ if completion_type == "module":
+ signature_text = "module " + completion_name
+ elif completion_type == "keyword":
+ signature_text = "keyword " + completion_name
+ else:
+ signature_text = ""
+ else:
+ merged_sig = "\n\n".join(
+ [
+ format_signature(
+ (
+ "def "
+ if completion_type == "function"
+ else "class "
+ if completion_type == "class"
+ else ""
+ ),
+ s,
+ )
+ for s in signature_strings
+ ]
+ )
+ signature_text = _md(
+ f"```python3\n{merged_sig}\n```",
+ apply_markdown_class=False,
+ ).text
+
+ body_converted = (
+ _convert_docstring_to_markdown(module_name, raw_body)
+ if raw_body
+ else ""
+ )
+
+ if signature_text and body_converted:
+ docstring = signature_text + "\n\n" + body_converted
+ else:
+ docstring = signature_text + body_converted
+
+ if init_docstring:
+ docstring += "\n\n" + init_docstring
+
+ return docstring
+
+
+def _convert_docstring_to_markdown(
+ module_name: str,
+ raw_docstring: str,
+) -> str:
+ """
+ Convert raw docstring to markdown or HTML, depending on module origin.
+ """
+ # for marimo docstrings, treat them as markdown
+ # for other modules, treat them as plain text
+ if module_name.startswith("marimo"):
+ # Convert Google-style docstrings to markdown, if applicable
+ if "Returns:" in raw_docstring or "Args:" in raw_docstring:
+ return _md(
+ google_docstring_to_markdown(raw_docstring),
+ apply_markdown_class=False,
+ ).text
+ else:
+ return _md(raw_docstring, apply_markdown_class=False).text
+ else:
+ # Possibly RST -> HTML
+ try:
+ return (
+ "<div class='external-docs'>"
+ + convert_rst_to_html(raw_docstring)
+ + "</div>"
+ )
+ except Exception:
+ # if docutils chokes, we don't want to crash the completion
+ # worker
+ return (
+ "<pre class='external-docs'>"
+ + html.escape(raw_docstring)
+ + "</pre>"
+ )
+
+
def _get_docstring(completion: jedi.api.classes.BaseName) -> str:
try:
- body = cast(str, completion.docstring(raw=True))
+ raw_body = cast(str, completion.docstring(raw=True))
except Exception:
LOGGER.debug("Failed to get docstring for %s", completion.name)
return ""
- if completion.type == "function":
- prefix = "def "
- elif completion.type == "class":
- prefix = "class "
- else:
- prefix = ""
-
+ # Glean raw signatures
try:
- signature_text = "\n\n".join(
- [
- format_signature(prefix, s.to_string())
- for s in completion.get_signatures()
- ]
+ signature_strings = tuple(
+ s.to_string() for s in completion.get_signatures()
)
except Exception:
LOGGER.debug("Maybe failed getting signature for %s", completion.name)
return ""
- if completion.type == "module" and not signature_text:
- signature_text = "module " + completion.name
- elif completion.type == "keyword" and not signature_text:
- signature_text = "keyword " + completion.name
-
- if signature_text:
- signature_text = _md(
- "```python3\n" + signature_text + "\n```",
- apply_markdown_class=False,
- ).text
-
- if body:
- # for marimo docstrings, treat them as markdown
- # for other modules, treat them as plain text
- if completion.module_name.startswith("marimo"):
- body = _md(body, apply_markdown_class=False).text
- else:
- try:
- body = (
- "<div class='external-docs'>"
- + convert_rst_to_html(body)
- + "</div>"
- )
- except Exception as e:
- # if docutils chokes, we don't want to crash the completion
- # worker
- LOGGER.debug("Converting RST to HTML failed: ", e)
- body = (
- "<pre class='external-docs'>"
- + html.escape(body)
- + "</pre>"
- )
-
- if signature_text and body:
- docstring = signature_text + "\n\n" + body
- else:
- docstring = signature_text + body
-
+ init_docstring = ""
if completion.type == "class":
- # Append the __init__ docstring.
- definitions = completion.goto()
+ # Possibly append the __init__ docstring, if it exists
+ definitions: list[jedi.api.classes.Name] = completion.goto()
if (
definitions
and len(definitions) == 1
and isinstance(definitions[0], jedi.api.classes.Name)
):
- name = definitions[0]
- for subname in name.defined_names():
+ for subname in definitions[0].defined_names():
if subname.name.endswith("__init__"):
- init_docstring = subname.docstring(raw=True)
- if init_docstring:
+ raw_init = subname.docstring(raw=True)
+ if raw_init:
init_docstring = (
"__init__ docstring:\n\n"
- + _md(
- init_docstring, apply_markdown_class=False
- ).text
+ + _md(raw_init, apply_markdown_class=False).text
)
- if docstring and init_docstring:
- docstring += "\n\n" + init_docstring
- else:
- docstring += init_docstring
- return docstring
+ # Build final docstring
+ return _build_docstring_cached(
+ completion.type,
+ completion.name,
+ str(completion.module_name),
+ signature_strings,
+ raw_body,
+ init_docstring or None,
+ )
def _get_type_hint(completion: jedi.api.classes.BaseName) -> str:
diff --git a/marimo/_utils/docs.py b/marimo/_utils/docs.py
new file mode 100644
index 0000000000..0bae403420
--- /dev/null
+++ b/marimo/_utils/docs.py
@@ -0,0 +1,164 @@
+import re
+from textwrap import dedent
+
+
+def google_docstring_to_markdown(docstring: str) -> str:
+ """
+ Converts a Google-style docstring to a rough Markdown format.
+
+ Args:
+ docstring (str): The raw Google-style docstring.
+
+ Returns:
+ str: A Markdown string that can be consumed by our doc-to-HTML converter.
+ """
+ if not docstring:
+ return ""
+
+ docstring_lines = docstring.splitlines()
+ if len(docstring_lines) > 1:
+ first_line = docstring_lines[0]
+ dedented_lines = dedent("\n".join(docstring_lines[1:]))
+ docstring = first_line + "\n" + dedented_lines
+
+ # Simple approach: split and parse line by line
+ lines = docstring.strip().splitlines()
+ parsed_lines: list[str] = []
+ arg_table: list[tuple[str, str, str]] = []
+ returns_table: list[tuple[str, str]] = []
+ raises_table: list[tuple[str, str]] = []
+ in_args = False
+ in_returns = False
+ in_raises = False
+ in_examples = False
+ examples_lines: list[str] = []
+
+ # We'll store a simple summary until we see "Args:" or "Returns:" or "Raises:"
+ for line in lines:
+ # Only strip the first 4 spaces
+ if line.startswith(" "):
+ stripped = line[4:]
+ else:
+ stripped = line.strip()
+
+ # Check for control keywords
+ if re.match(r"^Args:\s*$", stripped):
+ in_args = True
+ in_returns = False
+ in_raises = False
+ in_examples = False
+ continue
+ elif re.match(r"^Returns?:\s*$", stripped):
+ in_args = False
+ in_returns = True
+ in_raises = False
+ in_examples = False
+ continue
+ elif re.match(r"^Raises:\s*$", stripped):
+ in_args = False
+ in_returns = False
+ in_raises = True
+ in_examples = False
+ continue
+ elif re.match(r"^Examples?:\s*$", stripped):
+ in_args = False
+ in_returns = False
+ in_raises = False
+ in_examples = True
+ continue
+
+ if in_examples:
+ # Just capture all lines for examples block
+ examples_lines.append(stripped)
+ continue
+
+ # If within Args:
+ if in_args:
+ # Typically: " arg_name (arg_type): description"
+ match = re.match(r"^(\w+)\s*\(([^)]+)\):\s*(.*)", stripped)
+ if match:
+ arg_name, arg_type, description = match.groups()
+ arg_table.append((arg_name, arg_type, description.strip()))
+ else:
+ # Fallback to " arg_name: description"
+ match = re.match(r"^(\w+)\s*:\s*(.*)", stripped)
+ if match:
+ arg_name, description = match.groups()
+ arg_table.append((arg_name, "", description.strip()))
+ else:
+ # Possibly just an indented line continuing the description
+ if arg_table:
+ arg_table[-1] = (
+ arg_table[-1][0],
+ arg_table[-1][1],
+ arg_table[-1][2] + " " + stripped.strip(),
+ )
+ continue
+
+ # If within Returns:
+ if in_returns:
+ # Typically: " ReturnType: the big description"
+ match = re.match(r"^([^:]+):\s*(.*)", stripped)
+ if match:
+ ret_type, description = match.groups()
+ returns_table.append((ret_type.strip(), description.strip()))
+ else:
+ # Possibly just an indented line continuing
+ if returns_table:
+ returns_table[-1] = (
+ returns_table[-1][0],
+ returns_table[-1][1] + " " + stripped.strip(),
+ )
+ continue
+
+ # If within Raises:
+ if in_raises:
+ # Google style typically: " ErrorType: explanation"
+ match = re.match(r"^([^:]+):\s*(.*)", stripped)
+ if match:
+ err_type, explanation = match.groups()
+ # We'll just turn it into a "# Raises" heading
+ # and bullet lines for each raise
+ raises_table.append((err_type.strip(), explanation.strip()))
+ else:
+ # Possibly just an indented line continuing
+ if raises_table and raises_table[-1][1].startswith("- **"):
+ raises_table[-1] = (
+ raises_table[-1][0],
+ raises_table[-1][1] + " " + stripped.strip(),
+ )
+ continue
+
+ # Otherwise, treat it as summary or normal text
+ parsed_lines.append(stripped)
+
+ # Build final output
+ output: list[str] = []
+ if parsed_lines:
+ output.append("# Summary")
+ output.append("\n".join(parsed_lines).strip())
+
+ if arg_table:
+ output.append("\n# Arguments")
+ output.append("| Parameter | Type | Description |")
+ output.append("|-----------|------|-------------|")
+ for arg_name, arg_type, desc in arg_table:
+ output.append(f"| `{arg_name}` | `{arg_type}` | {desc.strip()} |")
+
+ if returns_table:
+ output.append("\n# Returns")
+ output.append("| Type | Description |")
+ output.append("|------|-------------|")
+ for ret_type, desc in returns_table:
+ output.append(f"| `{ret_type}` | {desc.strip()} |")
+
+ if raises_table:
+ output.append("\n# Raises")
+ for err_type, explanation in raises_table:
+ output.append(f"- **{err_type}**: {explanation.strip()}")
+
+ if examples_lines:
+ output.append("\n# Examples")
+ output.append("\n".join(examples_lines))
+
+ return "\n".join(output)
diff --git a/tests/_runtime/snapshots/docstrings_class.txt b/tests/_runtime/snapshots/docstrings_class.txt
new file mode 100644
index 0000000000..fce203d268
--- /dev/null
+++ b/tests/_runtime/snapshots/docstrings_class.txt
@@ -0,0 +1,8 @@
+<div class="codehilite"><pre><span></span><code><span class="k">class</span> <span class="nc">MyClass</span><span class="p">()</span>
+</code></pre></div>
+
+<span class="paragraph">Some docstring for the class.</span>
+
+__init__ docstring:
+
+Class init details.
\ No newline at end of file
diff --git a/tests/_runtime/snapshots/docstrings_function.txt b/tests/_runtime/snapshots/docstrings_function.txt
new file mode 100644
index 0000000000..cfc19f3242
--- /dev/null
+++ b/tests/_runtime/snapshots/docstrings_function.txt
@@ -0,0 +1,4 @@
+<div class="codehilite"><pre><span></span><code><span class="k">def</span> <span class="nf">my_func</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)</span>
+</code></pre></div>
+
+<span class="paragraph">This is a simple docstring for a function.</span>
\ No newline at end of file
diff --git a/tests/_runtime/snapshots/docstrings_function_external.txt b/tests/_runtime/snapshots/docstrings_function_external.txt
new file mode 100644
index 0000000000..4c191ca40d
--- /dev/null
+++ b/tests/_runtime/snapshots/docstrings_function_external.txt
@@ -0,0 +1,7 @@
+<div class="codehilite"><pre><span></span><code><span class="k">def</span> <span class="nf">my_func</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)</span>
+</code></pre></div>
+
+<div class='external-docs'><div class="document">
+<p>This is a simple docstring for a function.</p>
+</div>
+</div>
\ No newline at end of file
diff --git a/tests/_runtime/snapshots/docstrings_function_google.txt b/tests/_runtime/snapshots/docstrings_function_google.txt
new file mode 100644
index 0000000000..326801eece
--- /dev/null
+++ b/tests/_runtime/snapshots/docstrings_function_google.txt
@@ -0,0 +1,40 @@
+<div class="codehilite"><pre><span></span><code><span class="k">def</span> <span class="nf">my_func</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)</span>
+</code></pre></div>
+
+<h1 id="arguments">Arguments</h1>
+<table>
+<thead>
+<tr>
+<th>Parameter</th>
+<th>Type</th>
+<th>Description</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td><code>arg1</code></td>
+<td>``</td>
+<td>Description of arg1.</td>
+</tr>
+<tr>
+<td><code>arg2</code></td>
+<td>``</td>
+<td>Description of arg2.</td>
+</tr>
+</tbody>
+</table>
+<h1 id="returns">Returns</h1>
+<table>
+<thead>
+<tr>
+<th>Type</th>
+<th>Description</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td><code>HTML</code></td>
+<td>A description of the return value.</td>
+</tr>
+</tbody>
+</table>
\ No newline at end of file
diff --git a/tests/_runtime/snapshots/docstrings_keyword.txt b/tests/_runtime/snapshots/docstrings_keyword.txt
new file mode 100644
index 0000000000..0813839db9
--- /dev/null
+++ b/tests/_runtime/snapshots/docstrings_keyword.txt
@@ -0,0 +1 @@
+keyword yield
\ No newline at end of file
diff --git a/tests/_runtime/snapshots/docstrings_module.txt b/tests/_runtime/snapshots/docstrings_module.txt
new file mode 100644
index 0000000000..7e60ba06a9
--- /dev/null
+++ b/tests/_runtime/snapshots/docstrings_module.txt
@@ -0,0 +1 @@
+module os
\ No newline at end of file
diff --git a/tests/_runtime/test_complete.py b/tests/_runtime/test_complete.py
new file mode 100644
index 0000000000..d5ff588cdf
--- /dev/null
+++ b/tests/_runtime/test_complete.py
@@ -0,0 +1,111 @@
+from marimo._runtime.complete import _build_docstring_cached
+from tests.mocks import snapshotter
+
+snapshot = snapshotter(__file__)
+
+
+def test_build_docstring_function_no_init():
+ result = _build_docstring_cached(
+ completion_type="function",
+ completion_name="my_func",
+ module_name="marimo.my_module",
+ signature_strings=("my_func(arg1, arg2)",),
+ raw_body="This is a simple docstring for a function.",
+ init_docstring=None,
+ )
+ assert "my_func" in result
+ assert "This is a simple docstring for a function." in result
+ assert '<div class="codehilite">' in result
+ snapshot("docstrings_function.txt", result)
+
+
+def test_docstring_function_with_google_style():
+ result = _build_docstring_cached(
+ completion_type="function",
+ completion_name="my_func",
+ module_name="marimo.my_module",
+ signature_strings=("my_func(arg1, arg2)",),
+ raw_body="""
+ Args:
+ arg1: Description of arg1.
+ arg2: Description of arg2.
+
+ Returns:
+ HTML: A description of the return value.
+ """,
+ init_docstring=None,
+ )
+
+ assert "Description of arg1" in result
+ assert "Description of arg2" in result
+ assert "A description of the return value" in result
+ snapshot("docstrings_function_google.txt", result)
+
+
+def test_docstring_function_from_external_module():
+ result = _build_docstring_cached(
+ completion_type="function",
+ completion_name="my_func",
+ module_name="os",
+ signature_strings=("my_func(arg1, arg2)",),
+ raw_body="This is a simple docstring for a function.",
+ init_docstring=None,
+ )
+ assert "This is a simple docstring for a function." in result
+ assert "<div class='external-docs'>" in result
+ snapshot("docstrings_function_external.txt", result)
+
+
+def test_build_docstring_class_with_init():
+ result = _build_docstring_cached(
+ completion_type="class",
+ completion_name="MyClass",
+ module_name="marimo.some_class",
+ signature_strings=("MyClass()",),
+ raw_body="Some docstring for the class.",
+ init_docstring="__init__ docstring:\n\nClass init details.",
+ )
+ assert "MyClass" in result
+ assert "Some docstring for the class." in result
+ assert "Class init details." in result
+ snapshot("docstrings_class.txt", result)
+
+
+def test_build_docstring_module():
+ result = _build_docstring_cached(
+ completion_type="module",
+ completion_name="os",
+ module_name="os",
+ signature_strings=(),
+ raw_body=None,
+ init_docstring=None,
+ )
+ assert "module os" in result
+ assert "```python3" not in result
+ snapshot("docstrings_module.txt", result)
+
+
+def test_build_docstring_keyword():
+ result = _build_docstring_cached(
+ completion_type="keyword",
+ completion_name="yield",
+ module_name="",
+ signature_strings=(),
+ raw_body=None,
+ init_docstring=None,
+ )
+ assert "keyword yield" in result
+ assert "```python3" not in result
+ snapshot("docstrings_keyword.txt", result)
+
+
+def test_build_docstring_no_signature_no_body():
+ result = _build_docstring_cached(
+ completion_type="statement",
+ completion_name="random_statement",
+ module_name="random.module",
+ signature_strings=(),
+ raw_body=None,
+ init_docstring=None,
+ )
+ assert len(result.strip()) == 0
diff --git a/tests/_utils/snapshots/docstring_complex.txt b/tests/_utils/snapshots/docstring_complex.txt
new file mode 100644
index 0000000000..737368968b
--- /dev/null
+++ b/tests/_utils/snapshots/docstring_complex.txt
@@ -0,0 +1,34 @@
+# Summary
+Stack items vertically, in a column.
+Combine with `hstack` to build a grid of items.
+
+# Arguments
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `items` | `Sequence[object]` | A list of items. |
+| `align` | `Literal["start", "end", "center", "stretch"], optional` | Align items horizontally: start, end, center, or stretch. |
+| `justify` | `Literal["start", "center", "end", "space-between", "space-around"]` | Justify items vertically: start, center, end, space-between, or space-around. Defaults to "start". |
+| `gap` | `float, optional` | Gap between items as a float in rem. 1rem is 16px by default. Defaults to 0.5. |
+| `heights` | `Union[Literal["equal"], Sequence[float]], optional` | "equal" to give items equal height; or a list of relative heights with same length as `items`, eg, [1, 2] means the second item is twice as tall as the first; or None for a sensible default. |
+
+# Returns
+| Type | Description |
+|------|-------------|
+| `Html` | An Html object. |
+
+# Examples
+Build a column of items:
+```python
+# Build a column of items
+mo.vstack([mo.md("..."), mo.ui.text_area()])
+```
+Build a grid:
+```python
+# Build a grid.
+mo.vstack(
+ [
+ mo.hstack([mo.md("..."), mo.ui.text_area()]),
+ mo.hstack([mo.ui.checkbox(), mo.ui.text(), mo.ui.date()]),
+ ]
+)
+```
diff --git a/tests/_utils/snapshots/docstring_one_liner.txt b/tests/_utils/snapshots/docstring_one_liner.txt
new file mode 100644
index 0000000000..f54dd43a93
--- /dev/null
+++ b/tests/_utils/snapshots/docstring_one_liner.txt
@@ -0,0 +1,2 @@
+# Summary
+One-liner docstring
\ No newline at end of file
diff --git a/tests/_utils/snapshots/docstring_summary.txt b/tests/_utils/snapshots/docstring_summary.txt
new file mode 100644
index 0000000000..57af8a36da
--- /dev/null
+++ b/tests/_utils/snapshots/docstring_summary.txt
@@ -0,0 +1,22 @@
+# Summary
+This is the summary.
+
+# Arguments
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `foo` | `str` | Lorem ipsum |
+| `bar` | `int` | Dolor sit amet |
+
+# Returns
+| Type | Description |
+|------|-------------|
+| `bool` | Return description |
+
+# Raises
+- **ValueError**: Something about the value
+
+# Examples
+```python
+print('Hello, world!')
+print(foo, bar)
+```
\ No newline at end of file
diff --git a/tests/_utils/test_debounce.py b/tests/_utils/test_debounce.py
new file mode 100644
index 0000000000..fa651d7330
--- /dev/null
+++ b/tests/_utils/test_debounce.py
@@ -0,0 +1,35 @@
+import time
+
+from marimo._utils.debounce import debounce
+
+
+def test_debounce_basic():
+ invocation_count = 0
+
+ @debounce(0.05)
+ def my_fn():
+ nonlocal invocation_count
+ invocation_count += 1
+
+ my_fn()
+ my_fn()
+ assert invocation_count == 1
+ time.sleep(0.06)
+ my_fn()
+ assert invocation_count == 2
+
+
+def test_debounce_with_args():
+ captured_arg = None
+
+ @debounce(0.05)
+ def my_arg_fn(x: int):
+ nonlocal captured_arg
+ captured_arg = x
+
+ my_arg_fn(1)
+ my_arg_fn(2)
+ assert captured_arg == 1
+ time.sleep(0.06)
+ my_arg_fn(3)
+ assert captured_arg == 3
diff --git a/tests/_utils/test_docs.py b/tests/_utils/test_docs.py
new file mode 100644
index 0000000000..80f6f56b59
--- /dev/null
+++ b/tests/_utils/test_docs.py
@@ -0,0 +1,97 @@
+from marimo._utils.docs import google_docstring_to_markdown
+from tests.mocks import snapshotter
+
+snapshot = snapshotter(__file__)
+
+
+def test_google_docstring_to_markdown_summary():
+ docstring = """This is the summary.
+
+ Args:
+ foo (str): Lorem ipsum
+ bar (int): Dolor sit amet
+
+ Returns:
+ bool: Return description
+
+ Raises:
+ ValueError: Something about the value
+
+ Examples:
+ ```python
+ print('Hello, world!')
+ print(foo, bar)
+ ```
+ """
+ md_result = google_docstring_to_markdown(docstring)
+ snapshot("docstring_summary.txt", md_result)
+
+ for substr in [
+ "# Summary",
+ "This is the summary.",
+ "# Arguments",
+ "`foo`",
+ "`bar`",
+ "# Returns",
+ "`bool`",
+ "# Raises",
+ "ValueError",
+ "# Examples",
+ "```python",
+ "print('Hello, world!')",
+ ]:
+ assert substr in md_result
+
+
+def test_google_docstring_to_markdown_complex():
+ docstring = """
+ Stack items vertically, in a column.
+ Combine with `hstack` to build a grid of items.
+
+ Examples:
+ Build a column of items:
+ ```python
+ # Build a column of items
+ mo.vstack([mo.md("..."), mo.ui.text_area()])
+ ```
+ Build a grid:
+ ```python
+ # Build a grid.
+ mo.vstack(
+ [
+ mo.hstack([mo.md("..."), mo.ui.text_area()]),
+ mo.hstack([mo.ui.checkbox(), mo.ui.text(), mo.ui.date()]),
+ ]
+ )
+ ```
+
+ Args:
+ items (Sequence[object]): A list of items.
+ align (Literal["start", "end", "center", "stretch"], optional): Align items horizontally: start, end, center, or stretch.
+ justify (Literal["start", "center", "end", "space-between", "space-around"]):
+ Justify items vertically: start, center, end, space-between, or space-around.
+ Defaults to "start".
+ gap (float, optional): Gap between items as a float in rem. 1rem is 16px by default.
+ Defaults to 0.5.
+ heights (Union[Literal["equal"], Sequence[float]], optional): "equal" to give items
+ equal height; or a list of relative heights with same length as `items`,
+ eg, [1, 2] means the second item is twice as tall as the first;
+ or None for a sensible default.
+
+ Returns:
+ Html: An Html object.
+ """
+ md_result = google_docstring_to_markdown(docstring)
+ snapshot("docstring_complex.txt", md_result)
+
+
+def test_google_docstring_to_markdown_oneliner():
+ docstring = """One-liner docstring"""
+ md_result = google_docstring_to_markdown(docstring)
+ snapshot("docstring_one_liner.txt", md_result)
+
+ for substr in [
+ "# Summary",
+ "One-liner docstring",
+ ]:
+ assert substr in md_result