Skip to content

Commit 5b07811

Browse files
committed
Optimize also PyFrozenDict_New(frozendict)
1 parent 99d7ca6 commit 5b07811

2 files changed

Lines changed: 15 additions & 0 deletions

File tree

Lib/test/test_capi/test_dict.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -619,6 +619,16 @@ def test_frozendict_new(self):
619619
self.assertEqual(dct, frozendict(x=1, y=2))
620620
self.assertIs(type(dct), frozendict)
621621

622+
# PyFrozenDict_New(frozendict) returns the same object unmodified
623+
fd = frozendict(a=1, b=2, c=3)
624+
fd2 = frozendict_new(fd)
625+
self.assertIs(fd2, fd)
626+
627+
fd = FrozenDictSubclass(a=1, b=2, c=3)
628+
fd2 = frozendict_new(fd)
629+
self.assertIsNot(fd2, fd)
630+
self.assertEqual(fd2, fd)
631+
622632
# PyFrozenDict_New(NULL) creates an empty dictionary
623633
dct = frozendict_new(NULL)
624634
self.assertEqual(dct, frozendict())

Objects/dictobject.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8203,6 +8203,11 @@ PyObject*
82038203
PyFrozenDict_New(PyObject *iterable)
82048204
{
82058205
if (iterable != NULL) {
8206+
if (PyFrozenDict_CheckExact(iterable)) {
8207+
// PyFrozenDict_New(frozendict) returns the same object unmodified
8208+
return Py_NewRef(iterable);
8209+
}
8210+
82068211
PyObject *args = PyTuple_Pack(1, iterable);
82078212
if (args == NULL) {
82088213
return NULL;

0 commit comments

Comments
 (0)