https://github.com/python/cpython/commit/ca0cc5063301bb62a3a73ff1328144c91fa558bc
commit: ca0cc5063301bb62a3a73ff1328144c91fa558bc
branch: main
author: Pieter Eendebak <[email protected]>
committer: eendebakpt <[email protected]>
date: 2026-11-12T15:07:37+01:00
summary:

gh-110941: Fix json.dump encoding dict subclasses as empty (continued) (#150631)

* gh-110941: Fix `json.dump` encoding dict subclasses as empty.


Co-authored-by: Pieter Eendebak <[email protected]>
Co-authored-by: Alexander Ljungberg <[email protected]>

files:
A Misc/NEWS.d/next/Library/2023-10-18-13-31-10.gh-issue-110941.UVrYGE.rst
M Lib/test/test_json/test_default.py
M Modules/_json.c

diff --git a/Lib/test/test_json/test_default.py 
b/Lib/test/test_json/test_default.py
index 811880a15c80208..7f3ef8b8cb9f96c 100644
--- a/Lib/test/test_json/test_default.py
+++ b/Lib/test/test_json/test_default.py
@@ -1,7 +1,29 @@
 import collections
+import collections.abc
 from test.test_json import PyTest, CTest
 
 
+class CustomIndexDict(collections.abc.Mapping, dict):
+    # Using `Mapping` here to make this a complete dict subclass, but note the 
bug in #110941
+    # is not specific to `Mapping` subclasses and the outcome would have been 
the same with a
+    # fully manually implemented dict subclass.
+
+    def __init__(self, keys: tuple = ()):
+        self._keys = keys
+
+    def __getitem__(self, k):
+        try:
+            return self._keys.index(k)
+        except ValueError:
+            raise KeyError(k)
+
+    def __iter__(self):
+        return iter(self._keys)
+
+    def __len__(self):
+        return len(self._keys)
+
+
 class TestDefault:
     def test_default(self):
         self.assertEqual(
@@ -36,6 +58,23 @@ def test_ordereddict(self):
             self.dumps(od, sort_keys=True),
             '{"a": 1, "b": 2, "c": 3, "d": 4}')
 
+    # This should behave identically for PyTest and CTest: see #110941.
+    def test_custom_dict(self):
+        cd = CustomIndexDict(("b", "a"))
+        self.assertEqual(
+            self.dumps(cd),
+            '{"b": 0, "a": 1}')
+        self.assertEqual(
+            self.dumps(cd, sort_keys=True),
+            '{"a": 1, "b": 0}')
+
+    def test_empty_custom_dict(self):
+        # Exercise the fast path when a dict subclass is empty.
+        cd = CustomIndexDict()
+        self.assertEqual(
+            self.dumps(cd),
+            '{}')
+
 
 class TestPyDefault(TestDefault, PyTest): pass
 class TestCDefault(TestDefault, CTest): pass
diff --git 
a/Misc/NEWS.d/next/Library/2023-10-18-13-31-10.gh-issue-110941.UVrYGE.rst 
b/Misc/NEWS.d/next/Library/2023-10-18-13-31-10.gh-issue-110941.UVrYGE.rst
new file mode 100644
index 000000000000000..5824b593460e9be
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2023-10-18-13-31-10.gh-issue-110941.UVrYGE.rst
@@ -0,0 +1,2 @@
+Fix ``json.dump`` and ``json.dumps`` encoding certain dict subclasses as
+empty.
diff --git a/Modules/_json.c b/Modules/_json.c
index 3a724a3e72b185b..e79b697f06c994c 100644
--- a/Modules/_json.c
+++ b/Modules/_json.c
@@ -1802,7 +1802,10 @@ encoder_listencode_dict(PyEncoderObject *s, 
PyUnicodeWriter *writer,
     PyObject *ident = NULL;
     bool first = true;
 
-    if (PyDict_GET_SIZE(dct) == 0) {
+    // Only take the fast path for exact dicts: a subclass may keep its
+    // contents outside the dict storage, so PyDict_GET_SIZE could be 0 while
+    // the mapping is non-empty (gh-110941).
+    if (PyAnyDict_CheckExact(dct) && PyDict_GET_SIZE(dct) == 0) {
         /* Fast path */
         return PyUnicodeWriter_WriteASCII(writer, "{}", 2);
     }

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to