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: add support for formatting defaultdict with tree/json output (#4417)

Myles Scolnick8db97dc8ef24
diff --git a/marimo/_output/formatters/structures.py b/marimo/_output/formatters/structures.py
index 56dd2c4899..085f374232 100644
--- a/marimo/_output/formatters/structures.py
+++ b/marimo/_output/formatters/structures.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import json
import sys
+from collections import defaultdict
from typing import Any, Union
from marimo._messaging.mimetypes import KnownMimeType
@@ -63,8 +64,14 @@ class StructuresFormatter(FormatterFactory):
@formatting.formatter(list)
@formatting.formatter(tuple)
@formatting.formatter(dict)
+ @formatting.formatter(defaultdict)
def _format_structure(
- t: Union[tuple[Any, ...], list[Any], dict[str, Any]],
+ t: Union[
+ tuple[Any, ...],
+ list[Any],
+ dict[str, Any],
+ defaultdict[Any, Any],
+ ],
) -> tuple[KnownMimeType, str]:
# Some objects extend list/tuple/dict, but also have _repr_ methods
# that we want to use preferentially.
@@ -81,9 +88,16 @@ class StructuresFormatter(FormatterFactory):
elif isinstance(t, list) and type(t) is not list:
if str(t) != str(list(t)):
return plain_text.plain_text(str(t))._mime_()
- elif isinstance(t, dict) and type(t) is not dict:
+ elif (
+ isinstance(t, dict)
+ and type(t) is not dict
+ and type(t) is not defaultdict
+ ):
if str(t) != str(dict(t)):
return plain_text.plain_text(str(t))._mime_()
+ elif isinstance(t, defaultdict) and type(t) is not defaultdict:
+ if str(t) != str(defaultdict(t.default_factory, t)):
+ return plain_text.plain_text(str(t))._mime_()
if t and "matplotlib" in sys.modules:
# Special case for matplotlib:
diff --git a/marimo/_smoke_tests/structures.py b/marimo/_smoke_tests/structures.py
index 02e9528a2f..69cf11af57 100644
--- a/marimo/_smoke_tests/structures.py
+++ b/marimo/_smoke_tests/structures.py
@@ -1,11 +1,11 @@
import marimo
-__generated_with = "0.9.31"
+__generated_with = "0.12.4"
app = marimo.App(width="medium")
@app.cell
-def __(mo, x):
+def _(mo, x):
import datetime
[
@@ -35,7 +35,24 @@ def __(mo, x):
@app.cell
-def __():
+def _():
+ import random
+ from marimo._output.formatters.structures import format_structure
+ from collections import defaultdict
+
+ # Create a defaultdict with lists
+ random_data = defaultdict(list)
+
+ # Populate the defaultdict with random data
+ for i in range(10):
+ random_data[f"key_{i}"].extend(random.sample(range(100), 5))
+
+ random_data
+ return defaultdict, format_structure, i, random, random_data
+
+
+def _():
class CustomList(list):
def __init__(self, extra_arg):
super().__init__((1, 2))
@@ -46,13 +63,13 @@ def __():
@app.cell
-def __():
+def _():
import marimo as mo
return (mo,)
@app.cell
-def __():
+def _():
import sys
# Even though this extends tuple, we preserve the repr
@@ -61,38 +78,38 @@ def __():
@app.cell
-def __(sys):
+def _(sys):
repr(sys.version_info)
return
@app.cell
-def __(sys):
+def _(sys):
# Nested, so it is not preserved
(sys.version_info,)
return
@app.cell
-def __(sys):
+def _(sys):
{1, 2, 3, sys.version_info}
return
@app.cell
-def __():
+def _():
(1, 2, 3)
return
@app.cell
-def __(mo):
+def _(mo):
mo.refs()
return
@app.cell
-def __(mo):
+def _(mo):
x = 1
mo.defs()
return (x,)
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
index 2778b7a224..83402f8549 100644
--- a/tests/_cli/test_cli_export.py
+++ b/tests/_cli/test_cli_export.py
@@ -436,7 +436,15 @@ class TestExportHtmlSmokeTests:
file.write_text(inspect.getsource(mod), encoding="utf-8")
out = tmp_path / "out.html"
p = subprocess.run(
- ["marimo", "export", "html", str(file), "-o", str(out)],
+ [
+ "marimo",
+ "export",
+ "html",
+ str(file),
+ "-o",
+ str(out),
+ "--no-sandbox",
+ ],
capture_output=True,
)
self.assert_has_errors(p)
diff --git a/tests/_output/formatters/test_structures.py b/tests/_output/formatters/test_structures.py
index a85805e342..6c11504ebb 100644
--- a/tests/_output/formatters/test_structures.py
+++ b/tests/_output/formatters/test_structures.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import sys
+from collections import defaultdict
from typing import Any, cast
from marimo._dependencies.dependencies import DependencyManager
@@ -228,3 +229,31 @@ def test_format_structure_set() -> None:
def test_format_structure_tuple() -> None:
test_tuple = (1, 2, 3)
assert format_structure(test_tuple) == (1, 2, 3)
+
+
+def test_format_structure_defaultdict() -> None:
+ StructuresFormatter().register()
+
+ # Test with default factory as int
+ d = defaultdict(int)
+ d["a"] = 1
+ d["b"] = 2
+ # Access a key that doesn't exist yet - should use default factory
+ _ = d["c"]
+
+ assert get_and_format(d) == (
+ "application/json",
+ '{"a": 1, "b": 2, "c": 0}',
+ )
+
+ # Test with default factory as list
+ d = defaultdict(list)
+ d["a"].append(1)
+ d["b"].append(2)
+ # Access a key that doesn't exist yet - should use default factory
+ _ = d["c"]
+
+ assert get_and_format(d) == (
+ "application/json",
+ '{"a": [1], "b": [2], "c": []}',
+ )
diff --git a/tests/_utils/test_flatten.py b/tests/_utils/test_flatten.py
index 770414637a..af71491533 100644
--- a/tests/_utils/test_flatten.py
+++ b/tests/_utils/test_flatten.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+from collections import defaultdict
from typing import Any
import pytest
@@ -40,6 +41,21 @@ def test_flat_dict() -> None:
assert u([7, 8, 9]) == {1: 7, 2: 8, 3: 9}
+def test_flat_defaultdict() -> None:
+ x: defaultdict[int, int] = defaultdict(int, {1: 4, 2: 5, 3: 6})
+ v, u = flatten(x)
+ assert v == [4, 5, 6]
+ assert u(v) == x
+ assert u([7, 8, 9]) == {1: 7, 2: 8, 3: 9}
+
+ # Test with default_factory
+ y: defaultdict[int, list[int]] = defaultdict(list, {1: [4, 5], 2: [6, 7]})
+ v, u = flatten(y)
+ assert v == [4, 5, 6, 7]
+ assert u(v) == y
+ assert u([8, 9, 10, 11]) == {1: [8, 9], 2: [10, 11]}
+
+
def test_flat_empty_list() -> None:
x: L = []
v, u = flatten(x)