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.

Fix loguru messages not being printed (#8697)

Shahmir Varqha3682a4359043
diff --git a/marimo/_messaging/types.py b/marimo/_messaging/types.py
index 5977c53aab..d627ee87be 100644
--- a/marimo/_messaging/types.py
+++ b/marimo/_messaging/types.py
@@ -35,6 +35,28 @@ class NoopStream(Stream):
pass
+def _ensure_plain_str(s: str) -> str:
+ """Coerce str subclasses to plain ``str``.
+
+ Some libraries (e.g. loguru) emit str subclasses whose ``__slots__``
+ carry extra metadata (loguru's ``Message.record``). When such an
+ object reaches msgspec serialization the encoder may serialize the
+ slots/attributes instead of the string value, corrupting console output.
+ Converting to a bare ``str`` strips those attributes cheaply and is
+ a no-op for regular strings (``type(s) is str`` fast-path).
+
+ Raises TypeError for non-str inputs to preserve io.TextIOBase.write()
+ semantics.
+ """
+ if type(s) is not str:
+ if not isinstance(s, str): # pyright: ignore[reportUnnecessaryIsInstance]
+ raise TypeError( # pyright: ignore[reportUnreachable]
+ f"write() argument must be a str, not {type(s).__name__}"
+ )
+ return str(s)
+ return s
+
+
# These streams are not stoppable by users (we don't implement stop).
class Stdout(io.TextIOBase):
name = "stdout"
@@ -46,7 +68,9 @@ class Stdout(io.TextIOBase):
pass
def write(self, __s: str) -> int:
- return self._write_with_mimetype(__s, mimetype="text/plain")
+ return self._write_with_mimetype(
+ _ensure_plain_str(__s), mimetype="text/plain"
+ )
def _stop(self) -> None:
"""Tear down resources, if any."""
@@ -63,7 +87,9 @@ class Stderr(io.TextIOBase):
pass
def write(self, __s: str) -> int:
- return self._write_with_mimetype(__s, mimetype="text/plain")
+ return self._write_with_mimetype(
+ _ensure_plain_str(__s), mimetype="text/plain"
+ )
def _stop(self) -> None:
"""Tear down resources, if any."""
diff --git a/tests/_messaging/test_streams.py b/tests/_messaging/test_streams.py
index 40f5e97b58..c85f9b32ae 100644
--- a/tests/_messaging/test_streams.py
+++ b/tests/_messaging/test_streams.py
@@ -121,6 +121,58 @@ class TestStderr:
assert mocked_kernel.stderr.messages == ["hello", "there"]
+class TestStrSubclassCoercion:
+ """Verify str subclasses (e.g. loguru Message) are coerced to plain str."""
+
+ @staticmethod
+ async def test_stdout_str_subclass(
+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider
+ ) -> None:
+ await mocked_kernel.k.run(
+ [
+ exec_req.get(
+ """
+ import sys
+
+ class _TaggedStr(str):
+ pass
+
+ _msg = _TaggedStr("tagged hello")
+ _msg.extra = {"key": "value"}
+ sys.stdout.write(_msg)
+ """
+ )
+ ]
+ )
+ assert mocked_kernel.stdout.messages == ["tagged hello"]
+ for m in mocked_kernel.stdout.messages:
+ assert type(m) is str
+
+ @staticmethod
+ async def test_stderr_str_subclass(
+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider
+ ) -> None:
+ await mocked_kernel.k.run(
+ [
+ exec_req.get(
+ """
+ import sys
+
+ class _TaggedStr(str):
+ pass
+
+ _msg = _TaggedStr("tagged error")
+ _msg.record = {"level": "ERROR"}
+ sys.stderr.write(_msg)
+ """
+ )
+ ]
+ )
+ assert mocked_kernel.stderr.messages == ["tagged error"]
+ for m in mocked_kernel.stderr.messages:
+ assert type(m) is str
+
+
async def test_import_multiprocessing(
mocked_kernel: MockedKernel, exec_req: ExecReqProvider
) -> None:
diff --git a/tests/_messaging/test_types.py b/tests/_messaging/test_types.py
index e1adbe15f7..1bf372429f 100644
--- a/tests/_messaging/test_types.py
+++ b/tests/_messaging/test_types.py
@@ -1,6 +1,8 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import pytest
+
from marimo._messaging.mimetypes import KnownMimeType
from marimo._messaging.types import (
KernelMessage,
@@ -75,6 +77,59 @@ class TestStdoutStderr:
assert len(stderr.written_data) == 1
assert stderr.written_data[0] == ("Error message", "text/plain")
+ def test_stdout_coerces_str_subclass(self) -> None:
+ stdout = self.MockStdout()
+
+ class StrSubclass(str):
+ pass
+
+ msg = StrSubclass("hello")
+ msg.extra = {"key": "value"} # pyright: ignore[reportAttributeAccessIssue]
+
+ result = stdout.write(msg)
+ assert result == 5
+ data, mimetype = stdout.written_data[0]
+ assert data == "hello"
+ assert mimetype == "text/plain"
+ # The data stored should be a plain str, not the subclass
+ assert type(data) is str
+ assert not hasattr(data, "extra")
+
+ def test_stderr_coerces_str_subclass(self) -> None:
+ stderr = self.MockStderr()
+
+ class StrSubclass(str):
+ pass
+
+ msg = StrSubclass("error!")
+ msg.record = {"level": "ERROR", "message": "error!"} # pyright: ignore[reportAttributeAccessIssue]
+
+ result = stderr.write(msg)
+ assert result == 6
+ data, mimetype = stderr.written_data[0]
+ assert data == "error!"
+ assert mimetype == "text/plain"
+ assert type(data) is str
+ assert not hasattr(data, "record")
+
+ def test_plain_str_not_copied(self) -> None:
+ stdout = self.MockStdout()
+ plain = "hello"
+ stdout.write(plain)
+ data, _ = stdout.written_data[0]
+ # Plain str should pass through without creating a new object
+ assert data is plain
+
+ def test_non_str_raises_type_error(self) -> None:
+ stdout = self.MockStdout()
+ stderr = self.MockStderr()
+
+ for stream in (stdout, stderr):
+ with pytest.raises(TypeError, match="must be a str"):
+ stream.write(b"bytes") # pyright: ignore[reportArgumentType]
+ with pytest.raises(TypeError, match="must be a str"):
+ stream.write(123) # pyright: ignore[reportArgumentType]
+
def test_stdout_name(self) -> None:
stdout = self.MockStdout()
assert stdout.name == "stdout"