Skip to content

Don't error out when logging non-JSON serialisable values #516

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion eliot/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@ def json_default(o: object) -> object:
if isinstance(o, polars.Datetime):
return o.isoformat()

raise TypeError("Unsupported type")
# Fall back to repr() get _some_ useful value to log
return repr(o)


if platform.python_implementation() == "PyPy":
Expand Down
12 changes: 10 additions & 2 deletions eliot/tests/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ def test_numpy_not_imported(self):

This ensures NumPy isn't a hard dependency.
"""
with self.assertRaises(TypeError):
dumps([object()], default=json_default)
weird_val = object()
self.assertEqual(dumps([weird_val], default=json_default), dumps([repr(weird_val)]))
self.assertEqual(dumps(12, default=json_default), "12")

@skipUnless(np, "NumPy is not installed.")
Expand Down Expand Up @@ -206,3 +206,11 @@ class TestDataClass:
obj = TestDataClass(name="test", value=42)
serialized = loads(dumps(obj, default=json_default))
self.assertEqual(serialized, {"name": "test", "value": 42})

def test_unserializable(self):
"""Test that even values without dedicated JSON serialization
support dump without errors."""
def unserializable():
pass

self.assertEqual(dumps(unserializable, default=json_default), dumps(repr(unserializable)))