This commit is contained in:
Mahiro Hirakawa 2026-09-15 20:26:35 -04:00 committed by GitHub
commit 979ca50826
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 22 additions and 0 deletions

View file

@ -72,6 +72,7 @@ def safe_dumps(
return result
else:
# Fall back to string conversion for non-serializable objects.
seen.remove(id(obj))
try:
return _transform(key, strip_null_bytes(str(obj)))
except Exception:

View file

@ -75,6 +75,27 @@ def test_unserializable_object():
assert result == "Unserializable Object"
def test_repeated_unserializable_sibling_is_not_circular():
# The same non-serializable object appearing twice as siblings is not a
# circular reference and both occurrences must be serialized.
class Stringable:
def __str__(self):
return "value"
obj = Stringable()
assert json.loads(safe_dumps([obj, obj])) == ["value", "value"]
assert json.loads(safe_dumps({"a": obj, "b": obj})) == {
"a": "value",
"b": "value",
}
# A genuine self-cycle must still be reported.
cycle = {}
cycle["self"] = cycle
assert json.loads(safe_dumps(cycle))["self"] == "CircularReference Detected"
def test_non_standard_dict_keys():
try:
# Test handling of dictionaries with non-standard keys