Skip to content

Commit 6727967

Browse files
committed
Fix frozendict merge ("|=" operator); add tests
1 parent 6fca6d1 commit 6727967

File tree

2 files changed

+39
-4
lines changed

2 files changed

+39
-4
lines changed

Lib/test/test_dict.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1668,5 +1668,41 @@ class FrozenDictMappingTests(mapping_tests.BasicTestImmutableMappingProtocol):
16681668
type2test = frozendict
16691669

16701670

1671+
class FrozenDict(frozendict):
1672+
pass
1673+
1674+
1675+
class FrozenDictTests(unittest.TestCase):
1676+
def test_copy(self):
1677+
d = frozendict(x=1, y=2)
1678+
d2 = d.copy()
1679+
self.assertIs(d2, d)
1680+
1681+
d = FrozenDict(x=1, y=2)
1682+
d2 = d.copy()
1683+
self.assertIsNot(d2, d)
1684+
self.assertEqual(d2, frozendict(x=1, y=2))
1685+
self.assertEqual(type(d2), frozendict)
1686+
1687+
def test_merge(self):
1688+
# test "a | b" operator
1689+
self.assertEqual(frozendict(x=1) | frozendict(y=2),
1690+
frozendict({'x': 1, 'y': 2}))
1691+
self.assertEqual(frozendict(x=1) | dict(y=2),
1692+
frozendict({'x': 1, 'y': 2}))
1693+
self.assertEqual(frozendict(x=1, y=2) | frozendict(y=5),
1694+
frozendict({'x': 1, 'y': 5}))
1695+
1696+
def test_update(self):
1697+
# test "a |= b" operator
1698+
d = frozendict(x=1)
1699+
copy = d
1700+
self.assertIs(copy, d)
1701+
d |= frozendict(y=2)
1702+
self.assertIsNot(copy, d)
1703+
self.assertEqual(d, frozendict({'x': 1, 'y': 2}))
1704+
self.assertEqual(copy, frozendict({'x': 1}))
1705+
1706+
16711707
if __name__ == "__main__":
16721708
unittest.main()

Objects/dictobject.c

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4096,6 +4096,9 @@ static PyObject *
40964096
dict_copy_impl(PyDictObject *self)
40974097
/*[clinic end generated code: output=ffb782cf970a5c39 input=73935f042b639de4]*/
40984098
{
4099+
if (PyFrozenDict_CheckExact(self)) {
4100+
return Py_NewRef(self);
4101+
}
40994102
return PyDict_Copy((PyObject *)self);
41004103
}
41014104

@@ -4231,10 +4234,6 @@ PyDict_Copy(PyObject *o)
42314234
return NULL;
42324235
}
42334236

4234-
if (PyFrozenDict_CheckExact(o)) {
4235-
return Py_NewRef(o);
4236-
}
4237-
42384237
PyObject *res;
42394238
Py_BEGIN_CRITICAL_SECTION(o);
42404239

0 commit comments

Comments
 (0)