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: better formatting for google docstrings (#5750)

Shahmir Varqha5bb386cba6ce
diff --git a/marimo/_save/save.py b/marimo/_save/save.py
index 6dfdd88c5a..4660a6ef51 100644
--- a/marimo/_save/save.py
+++ b/marimo/_save/save.py
@@ -871,20 +871,6 @@ def persistent_cache( # type: ignore[misc]
**Warning.** Since context abuses sys frame trace, this may conflict with
debugging 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.
- 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.
`persistent_cache` can also be used as a drop in function-level memoization
@@ -910,6 +896,17 @@ def persistent_cache( # type: ignore[misc]
```
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()`
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
diff --git a/marimo/_utils/docs.py b/marimo/_utils/docs.py
index f48ae0d862..20614cba1f 100644
--- a/marimo/_utils/docs.py
+++ b/marimo/_utils/docs.py
@@ -43,25 +43,55 @@ def google_docstring_to_markdown(docstring: str) -> str:
def _handle_arg_or_attribute(
table: list[tuple[str, str, str]], stripped: str
) -> None:
- # Typically: " arg_name (arg_type): description"
- match = re.match(r"^(\w+)\s*\(([^)]+)\):\s*(.*)", stripped)
+ # Parse standard parameters: "arg_name (arg_type): description" or "arg_name: description"
+ # This handles both typed and untyped parameters, with or without description
+ match = re.match(r"^(\w+)(?:\s*\(([^)]+)\))?:\s*(.*)", stripped)
if match:
arg_name, arg_type, description = match.groups()
- 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()
- table.append((arg_name, "", description.strip()))
- else:
- # Possibly just an indented line continuing the description
- if table:
- table[-1] = (
- table[-1][0],
- table[-1][1],
- table[-1][2] + " " + stripped.strip(),
- )
+ table.append((arg_name, arg_type or "", description.strip()))
+ return
+
+ # Parse special parameters: "*args: description" or "**kwargs: description"
+ if stripped.startswith("*args:"):
+ table.append(("*args", "", stripped[6:].strip()))
+ return
+ if stripped.startswith("**kwargs:"):
+ table.append(("**kwargs", "", stripped[9:].strip()))
+ return
+
+ # Handle continuation lines
+ if not table:
+ return
+
+ current_name, current_type, current_desc = table[-1]
+ stripped_content = stripped.strip()
+
+ # Handle bullet points
+ if stripped_content.startswith("- "):
+ bullet_content = stripped_content[2:]
+ new_desc = (
+ current_desc + "<br>- " + bullet_content
+ if current_desc
+ else "- " + bullet_content
+ )
+ table[-1] = (current_name, current_type, new_desc)
+ return
+
+ # Check if we're inside a code block
+ if "```" in current_desc and not current_desc.rstrip().endswith("```"):
+ table[-1] = (
+ current_name,
+ current_type,
+ current_desc + "\n" + stripped_content,
+ )
+ return
+
+ # Regular continuation - add space separator
+ table[-1] = (
+ current_name,
+ current_type,
+ current_desc + " " + stripped_content,
+ )
# We'll store a simple summary until we see "Args:" or "Returns:" or "Raises:"
for line in lines:
@@ -175,14 +205,22 @@ def google_docstring_to_markdown(docstring: str) -> str:
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()} |")
+ # Process code blocks in the description
+ processed_desc = _process_code_block_content(desc.strip())
+ output.append(
+ f"| `{arg_name}` | `{arg_type}` | {processed_desc} |"
+ )
if attribute_table:
output.append("\n# Attributes")
output.append("| Attribute | Type | Description |")
output.append("|-----------|------|-------------|")
for arg_name, arg_type, desc in attribute_table:
- output.append(f"| `{arg_name}` | `{arg_type}` | {desc.strip()} |")
+ # Process code blocks in the description
+ processed_desc = _process_code_block_content(desc.strip())
+ output.append(
+ f"| `{arg_name}` | `{arg_type}` | {processed_desc} |"
+ )
if returns_table:
output.append("\n# Returns")
@@ -217,3 +255,30 @@ class MarimoConverter:
return True
return False
+
+
+def _process_code_block_content(description: str) -> str:
+ """
+ Process a description that may contain code blocks and convert them to HTML.
+
+ Args:
+ description (str): The description text that may contain ``` code blocks
+
+ Returns:
+ str: The description with code blocks converted to HTML <pre><code> tags
+ """
+ if "```" not in description:
+ return description
+
+ def replace_code_block(match: re.Match[str]) -> str:
+ code_content = match.group(1).strip()
+ if code_content.startswith("python\n"):
+ code_content = code_content[7:] # Remove "python\n"
+
+ return (
+ f"<pre><code>{code_content.replace(chr(10), '<br>')}</code></pre>"
+ )
+
+ return re.sub(
+ r"```(.*?)```", replace_code_block, description, flags=re.DOTALL
+ )
diff --git a/tests/_utils/snapshots/docstring_complex.txt b/tests/_utils/snapshots/docstring_complex.md
similarity index 68%
rename from tests/_utils/snapshots/docstring_complex.txt
rename to tests/_utils/snapshots/docstring_complex.md
index 38c40ff1d0..0d63784be3 100644
--- a/tests/_utils/snapshots/docstring_complex.txt
+++ b/tests/_utils/snapshots/docstring_complex.md
@@ -28,6 +28,12 @@ mo.vstack(
| `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. |
+| `custom_css` | `dict[str, str], optional` | Custom CSS styles for each column. Keys include:<br>- width<br>- height<br>- background_color<br>- border<br>- border_radius<br>- padding |
+| `typeless` | `` | Pass unknown types to the stack. |
+| `*args` | `` | positional arguments passed to stack |
+| `code_block` | `str` | Render a code block in the stack. <pre><code>mo.vstack(),<br>mo.hstack()</code></pre> |
+| `second_code_block` | `str` | Render a second code block in the stack. <pre><code>mo.vstack([])</code></pre> |
+| `**kwargs` | `` | keyword arguments passed to stack |
# Returns
| Type | Description |
diff --git a/tests/_utils/snapshots/docstring_one_liner.txt b/tests/_utils/snapshots/docstring_one_liner.md
similarity index 100%
rename from tests/_utils/snapshots/docstring_one_liner.txt
rename to tests/_utils/snapshots/docstring_one_liner.md
diff --git a/tests/_utils/snapshots/docstring_summary.md b/tests/_utils/snapshots/docstring_summary.md
new file mode 100644
index 0000000000..fc52f6a989
--- /dev/null
+++ b/tests/_utils/snapshots/docstring_summary.md
@@ -0,0 +1,28 @@
+# Summary
+This is the summary.
+
+# Examples
+```python
+print('Hello, world!')
+print(foo, bar)
+```
+
+# Arguments
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `foo` | `str` | Lorem ipsum |
+| `bar` | `int` | Dolor sit amet |
+
+# Attributes
+| Attribute | Type | Description |
+|-----------|------|-------------|
+| `baz` | `str` | Lorem ipsum |
+| `boo` | `int` | Dolor sit amet |
+
+# Returns
+| Type | Description |
+|------|-------------|
+| `bool` | Return description |
+
+# Raises
+- **ValueError**: Something about the value
\ No newline at end of file
diff --git a/tests/_utils/snapshots/docstring_summary.txt b/tests/_utils/snapshots/docstring_summary.txt
index fc52f6a989..3d9475eb91 100644
--- a/tests/_utils/snapshots/docstring_summary.txt
+++ b/tests/_utils/snapshots/docstring_summary.txt
@@ -11,13 +11,13 @@ print(foo, bar)
| Parameter | Type | Description |
|-----------|------|-------------|
| `foo` | `str` | Lorem ipsum |
-| `bar` | `int` | Dolor sit amet |
+| `bar` | `int` | Dolor sit amet. |
# Attributes
| Attribute | Type | Description |
|-----------|------|-------------|
| `baz` | `str` | Lorem ipsum |
-| `boo` | `int` | Dolor sit amet |
+| `boo` | `int` | Dolor sit amet. |
# Returns
| Type | Description |
diff --git a/tests/_utils/test_docs.py b/tests/_utils/test_docs.py
index 196822815f..bb9b6b34f3 100644
--- a/tests/_utils/test_docs.py
+++ b/tests/_utils/test_docs.py
@@ -1,4 +1,7 @@
-from marimo._utils.docs import google_docstring_to_markdown
+from marimo._utils.docs import (
+ _process_code_block_content,
+ google_docstring_to_markdown,
+)
from tests.mocks import snapshotter
snapshot = snapshotter(__file__)
@@ -28,7 +31,7 @@ def test_google_docstring_to_markdown_summary():
```
"""
md_result = google_docstring_to_markdown(docstring)
- snapshot("docstring_summary.txt", md_result)
+ snapshot("docstring_summary.md", md_result)
for substr in [
"# Summary",
@@ -84,21 +87,89 @@ def test_google_docstring_to_markdown_complex():
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.
+ custom_css (dict[str, str], optional): Custom CSS styles for each column. Keys include:
+ - width
+ - height
+ - background_color
+ - border
+ - border_radius
+ - padding
+ typeless: Pass unknown types to the stack.
+ *args: positional arguments passed to stack
+ code_block (str): Render a code block in the stack.
+ ```
+ mo.vstack(),
+ mo.hstack()
+ ```
+ second_code_block (str): Render a second code block in the stack.
+ ```python
+ mo.vstack([])
+ ```
+ **kwargs: keyword arguments passed to stack
Returns:
Html: An Html object.
"""
md_result = google_docstring_to_markdown(docstring)
- snapshot("docstring_complex.txt", md_result)
+
+ assert "<pre><code>mo.vstack(),<br>mo.hstack()</code></pre>" in md_result
+ assert "<pre><code>mo.vstack([])</code></pre>" in md_result
+
+ snapshot("docstring_complex.md", 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)
+ snapshot("docstring_one_liner.md", md_result)
for substr in [
"# Summary",
"One-liner docstring",
]:
assert substr in md_result
+
+
+def test_process_code_block_content():
+ """Test the _process_code_block_content function with various inputs."""
+
+ # Test with no code blocks
+ result = _process_code_block_content("Simple description")
+ assert result == "Simple description"
+
+ # Test with a simple code block
+ result = _process_code_block_content(
+ "Description with ```python\ncode here\n```"
+ )
+ assert result == "Description with <pre><code>code here</code></pre>"
+
+ # Test with code block without language
+ result = _process_code_block_content(
+ "Description with ```\ncode here\n```"
+ )
+ assert result == "Description with <pre><code>code here</code></pre>"
+
+ # Test with multiple code blocks
+ result = _process_code_block_content(
+ "First ```python\ncode1\n``` Second ```\ncode2\n```"
+ )
+ assert (
+ result
+ == "First <pre><code>code1</code></pre> Second <pre><code>code2</code></pre>"
+ )
+
+ # Test with text after code block
+ result = _process_code_block_content(
+ "Description ```python\ncode\n``` and more text"
+ )
+ assert result == "Description <pre><code>code</code></pre> and more text"
+
+ # Test with language identifier
+ result = _process_code_block_content(
+ "Description ```python\ncode here\n```"
+ )
+ assert result == "Description <pre><code>code here</code></pre>"
+
+ # Test with empty code block
+ result = _process_code_block_content("Description ```\n\n```")
+ assert result == "Description <pre><code></code></pre>"