Skip to content
Draft
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
15 changes: 15 additions & 0 deletions Lib/test/test_defaultdict.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,5 +204,20 @@ def default_factory():
self.assertEqual(test_dict[key], 2)
self.assertEqual(count, 2)

def test_repr_recursive_factory(self):
# gh-145492: defaultdict.__repr__ should not cause infinite recursion
# when the factory's __repr__ calls repr() on the defaultdict.
class ProblematicFactory:
def __call__(self):
return {}
def __repr__(self):
repr(dd)
return "ProblematicFactory()"

dd = defaultdict(ProblematicFactory())
# Should not raise RecursionError
r = repr(dd)
self.assertIn('ProblematicFactory()', r)

if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix infinite recursion in :class:`collections.defaultdict` ``__repr__``
when a ``defaultdict`` contains itself. Based on analysis by KowalskiThomas
in :gh:`145492`.
5 changes: 3 additions & 2 deletions Modules/_collectionsmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -2337,9 +2337,10 @@ defdict_repr(defdictobject *dd)
}
defrepr = PyUnicode_FromString("...");
}
else
else {
defrepr = PyObject_Repr(dd->default_factory);
Py_ReprLeave(dd->default_factory);
Py_ReprLeave(dd->default_factory);
}
}
if (defrepr == NULL) {
Py_DECREF(baserepr);
Expand Down
Loading