Skip to content

Commit dd64e42

Browse files
eendebakptblurb-it[bot]vstinner
authored
gh-141510: Implement copy and deepcopy for frozendict (#144905)
Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com> Co-authored-by: Victor Stinner <vstinner@python.org>
1 parent 7ac0868 commit dd64e42

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

Lib/copy.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def copy(x):
101101

102102

103103
_copy_atomic_types = frozenset({types.NoneType, int, float, bool, complex, str, tuple,
104-
bytes, frozenset, type, range, slice, property,
104+
bytes, frozendict, frozenset, type, range, slice, property,
105105
types.BuiltinFunctionType, types.EllipsisType,
106106
types.NotImplementedType, types.FunctionType, types.CodeType,
107107
weakref.ref, super})
@@ -203,6 +203,11 @@ def _deepcopy_dict(x, memo, deepcopy=deepcopy):
203203
return y
204204
d[dict] = _deepcopy_dict
205205

206+
def _deepcopy_frozendict(x, memo, deepcopy=deepcopy):
207+
y = _deepcopy_dict(x, memo, deepcopy)
208+
return frozendict(y)
209+
d[frozendict] = _deepcopy_frozendict
210+
206211
def _deepcopy_method(x, memo): # Copy instance methods
207212
return type(x)(x.__func__, deepcopy(x.__self__, memo))
208213
d[types.MethodType] = _deepcopy_method

Lib/test/test_copy.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,12 @@ def test_copy_dict(self):
133133
self.assertEqual(y, x)
134134
self.assertIsNot(y, x)
135135

136+
def test_copy_frozendict(self):
137+
x = frozendict(x=1, y=2)
138+
self.assertIs(copy.copy(x), x)
139+
x = frozendict()
140+
self.assertIs(copy.copy(x), x)
141+
136142
def test_copy_set(self):
137143
x = {1, 2, 3}
138144
y = copy.copy(x)
@@ -419,6 +425,13 @@ def test_deepcopy_dict(self):
419425
self.assertIsNot(x, y)
420426
self.assertIsNot(x["foo"], y["foo"])
421427

428+
def test_deepcopy_frozendict(self):
429+
x = frozendict({"foo": [1, 2], "bar": 3})
430+
y = copy.deepcopy(x)
431+
self.assertEqual(y, x)
432+
self.assertIsNot(x, y)
433+
self.assertIsNot(x["foo"], y["foo"])
434+
422435
@support.skip_emscripten_stack_overflow()
423436
@support.skip_wasi_stack_overflow()
424437
def test_deepcopy_reflexive_dict(self):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
The :mod:`copy` module now supports the :class:`frozendict` type. Patch by
2+
Pieter Eendebak based on work by Victor Stinner.

0 commit comments

Comments
 (0)