Skip to content

Commit f317c1b

Browse files
committed
Optimize deepcopy of empty containers
1 parent 1a84bdc commit f317c1b

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

Lib/copy.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -123,19 +123,23 @@ def deepcopy(x, memo=None, _nil=[]):
123123

124124
cls = type(x)
125125

126-
if cls in _atomic_types:
126+
if cls in _atomic_types or (cls in _immutable_iterables and len(x) == 0):
127127
return x
128128

129-
d = id(x)
130129
if memo is None:
130+
if cls in _mutable_iterables and len(x) == 0:
131+
return cls()
132+
d = id(x)
131133
memo = {}
132134
else:
135+
d = id(x)
133136
y = memo.get(d, _nil)
134137
if y is not _nil:
135138
return y
136139

137-
copier = _deepcopy_dispatch.get(cls)
138-
if copier is not None:
140+
if cls in _mutable_iterables and len(x) == 0:
141+
y = cls()
142+
elif copier := _deepcopy_dispatch.get(cls):
139143
y = copier(x, memo)
140144
else:
141145
if issubclass(cls, type):
@@ -173,6 +177,8 @@ def deepcopy(x, memo=None, _nil=[]):
173177
_atomic_types = {types.NoneType, types.EllipsisType, types.NotImplementedType,
174178
int, float, bool, complex, bytes, str, types.CodeType, type, range,
175179
types.BuiltinFunctionType, types.FunctionType, weakref.ref, property}
180+
_mutable_iterables = {list, dict, set}
181+
_immutable_iterables = {tuple, frozenset}
176182

177183
_deepcopy_dispatch = d = {}
178184

0 commit comments

Comments
 (0)