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
fix: correctness of formatting (#3644)
Myles Scolnickb8bd48663406
diff --git a/frontend/e2e-tests/shutdown.spec.ts b/frontend/e2e-tests/shutdown.spec.tsindex 93b90fa45c..2d0f8657df 100644--- a/frontend/e2e-tests/shutdown.spec.ts+++ b/frontend/e2e-tests/shutdown.spec.ts@@ -10,7 +10,7 @@ test("can resume a session", async ({ page }) => {const appUrl = getAppUrl("shutdown.py");await page.goto(appUrl);- await expect(page.getByText("None", { exact: true })).toBeVisible();+ await expect(page.getByText("'None'", { exact: true })).toBeVisible();// type in the formawait page.locator("#output-Hbol").getByRole("textbox").fill("12345");// shift enter to run the form@@ -51,7 +51,7 @@ test("restart kernel", async ({ page }) => {await confirmButton.waitFor({ state: "visible" });await confirmButton.click();- await expect(page.getByText("None", { exact: true })).toBeVisible();+ await expect(page.getByText("'None'", { exact: true })).toBeVisible();});test("shutdown shows disconnected text", async ({ page }) => {diff --git a/marimo/_output/formatting.py b/marimo/_output/formatting.pyindex 81896a1afa..79daa98c62 100644--- a/marimo/_output/formatting.py+++ b/marimo/_output/formatting.py@@ -174,9 +174,15 @@ class FormattedOutput:traceback: Optional[str] = Noneexception: BaseException | None = None+ @staticmethod+ def empty() -> FormattedOutput:+ return FormattedOutput(mimetype="text/plain", data="")+def try_format(obj: Any, include_opinionated: bool = True) -> FormattedOutput:- obj = "" if obj is None else obj+ if obj is None:+ return FormattedOutput.empty()+if (formatter := get_formatter(obj, include_opinionated=include_opinionated@@ -204,31 +210,24 @@ def try_format(obj: Any, include_opinionated: bool = True) -> FormattedOutput:else:glbls = ctx.globals- tb = Nonetry:# convert the object to a string using the kernel globals;# some libraries like duckdb introspect globals() ...- data = eval("str(obj)", glbls, {"obj": obj})+ data_str: str = eval("repr(obj)", glbls, {"obj": obj})except Exception:- tb = traceback.format_exc()return FormattedOutput(mimetype="text/plain",data="",- traceback=tb,+ traceback=traceback.format_exc(),)else:return (FormattedOutput(mimetype="text/html",- data=plain_text(escape(data)).text,- traceback=tb,- )- if data- else FormattedOutput(- mimetype="text/plain",- data="",- traceback=tb,+ data=plain_text(escape(data_str)).text,)+ if data_str+ else FormattedOutput.empty())diff --git a/tests/_messaging/test_variables.py b/tests/_messaging/test_variables.pyindex 5a53977993..66f75e43b9 100644--- a/tests/_messaging/test_variables.py+++ b/tests/_messaging/test_variables.py@@ -211,7 +211,7 @@ def test_get_variable_preview_dataframe(df: Any) -> None:mem_diff_mb = (mem_after - mem_before) / (1024 * 1024)- assert mem_diff_mb < 1, (+ assert mem_diff_mb < 10, (f"Memory increased by {mem_diff_mb}MB during preview")assert "2 columns" in previewdiff --git a/tests/_output/test_try_format.py b/tests/_output/test_try_format.pyindex 9e1a5c192f..a52055c52e 100644--- a/tests/_output/test_try_format.py+++ b/tests/_output/test_try_format.py@@ -77,16 +77,27 @@ def is_html(output: FormattedOutput) -> bool:def test_primitives():- # 1 and "1" are printed the same+ # 1 and "1" are differentassert try_format(1).data == "<pre style='font-size: 12px'>1</pre>"- assert try_format("1").data == "<pre style='font-size: 12px'>1</pre>"assert (- try_format("hello").data == "<pre style='font-size: 12px'>hello</pre>"+ try_format("1").data+ == "<pre style='font-size: 12px'>'1'</pre>"+ )+ assert (+ try_format("hello").data+ == "<pre style='font-size: 12px'>'hello'</pre>"+ )+ assert (+ try_format("").data+ == "<pre style='font-size: 12px'>''</pre>")assert try_format(None).data == ""- # True and 'True' are printed the same+ # True and 'True' are differentassert try_format(True).data == "<pre style='font-size: 12px'>True</pre>"- assert try_format("True").data == "<pre style='font-size: 12px'>True</pre>"+ assert (+ try_format("True").data+ == "<pre style='font-size: 12px'>'True'</pre>"+ )assert try_format(False).data == "<pre style='font-size: 12px'>False</pre>"assert try_format(1.0).data == "<pre style='font-size: 12px'>1.0</pre>"assert (@@ -169,7 +180,7 @@ def test_opinionated_formatter():assert "test" in result.data.lower()-def test_fallback_string_representation():+def test_does_not_use_only_str_repr():"""Test fallback to string representation for objects without formatters."""class NoFormatter:@@ -179,21 +190,8 @@ def test_fallback_string_representation():obj = NoFormatter()result = try_format(obj)assert is_html(result)- assert "no formatter" in result.data.lower()---def test_string_eval_error():- """Test handling of string evaluation errors."""-- class BadString:- def __str__(self):- raise ValueError("Bad string")-- obj = BadString()- result = try_format(obj)- assert result.mimetype == "text/plain"- assert result.data == ""- assert result.traceback is not None+ assert result.data.startswith("<pre style='font-size: 12px'>")+ assert "test_does_not_use_only_str_repr" in result.data.lower()def test_str_vs_repr():@@ -209,8 +207,8 @@ def test_str_vs_repr():obj = StrReprTest()result = try_format(obj)assert is_html(result)- assert "str_value" in result.data.lower()- assert "repr_value" not in result.data.lower()+ assert "str_value" not in result.data.lower()+ assert "repr_value" in result.data.lower()def test_repr_fallback():@@ -226,8 +224,8 @@ def test_repr_fallback():assert "repr_value" in result.data.lower()-def test_str_error_repr_fallback():- """Test that repr is used when str raises error."""+def test_repr_is_used_over_str():+ """Test that repr is used over str when both are available."""class StrErrorTest:def __str__(self):@@ -238,9 +236,8 @@ def test_str_error_repr_fallback():obj = StrErrorTest()result = try_format(obj)- assert result.mimetype == "text/plain"- assert result.data == ""- assert result.traceback is not None+ assert is_html(result)+ assert result.data == "<pre style='font-size: 12px'>repr_value</pre>"@pytest.mark.skipif(@@ -253,4 +250,4 @@ def test_numpy_array():obj = np.array([1, 2, 3])result = try_format(obj)assert is_html(result)- assert result.data == "<pre style='font-size: 12px'>[1 2 3]</pre>"+ assert result.data == "<pre style='font-size: 12px'>array([1, 2, 3])</pre>"