Skip to content

Commit d2fbcd8

Browse files
committed
Implement copy and deepcopy for frozendict
1 parent 6ef2578 commit d2fbcd8

2 files changed

Lines changed: 21 additions & 2 deletions

File tree

Lib/copy.py

Lines changed: 8 additions & 2 deletions
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})
@@ -166,7 +166,7 @@ def deepcopy(x, memo=None):
166166
int, float, bool, complex, bytes, str, types.CodeType, type, range,
167167
types.BuiltinFunctionType, types.FunctionType, weakref.ref, property})
168168

169-
_deepcopy_dispatch = d = {}
169+
d = {}
170170

171171

172172
def _deepcopy_list(x, memo, deepcopy=deepcopy):
@@ -203,10 +203,16 @@ 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
209214

215+
_deepcopy_dispatch = frozendict(d)
210216
del d
211217

212218
def _keep_alive(x, memo):

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 = {"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):

0 commit comments

Comments
 (0)