Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions Lib/copy.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,17 +169,20 @@ def deepcopy(x, memo=None):
_deepcopy_dispatch = d = {}


def _deepcopy_list(x, memo, deepcopy=deepcopy):
def _deepcopy_list(x, memo, deepcopy=deepcopy, _atomic=_atomic_types):
y = []
memo[id(x)] = y
append = y.append
for a in x:
append(deepcopy(a, memo))
# Inline the atomic-type check so atomic elements (int, str, None, ...)
# skip the deepcopy() call overhead entirely; deepcopy() would just
# return them unchanged after the same check.
append(a if type(a) in _atomic else deepcopy(a, memo))
return y
d[list] = _deepcopy_list

def _deepcopy_tuple(x, memo, deepcopy=deepcopy):
y = [deepcopy(a, memo) for a in x]
def _deepcopy_tuple(x, memo, deepcopy=deepcopy, _atomic=_atomic_types):
y = [a if type(a) in _atomic else deepcopy(a, memo) for a in x]
# We're not going to put the tuple in the memo, but it's still important we
# check for it, in case the tuple contains recursive mutable structures.
try:
Expand All @@ -195,11 +198,15 @@ def _deepcopy_tuple(x, memo, deepcopy=deepcopy):
return y
d[tuple] = _deepcopy_tuple

def _deepcopy_dict(x, memo, deepcopy=deepcopy):
def _deepcopy_dict(x, memo, deepcopy=deepcopy, _atomic=_atomic_types):
y = {}
memo[id(x)] = y
for key, value in x.items():
y[deepcopy(key, memo)] = deepcopy(value, memo)
# Inline the atomic-type check for keys and values: atomic objects
# (str keys, int/str/None values, ...) are returned as-is by
# deepcopy(), so skip the per-item call in that common case.
y[key if type(key) in _atomic else deepcopy(key, memo)] = (
value if type(value) in _atomic else deepcopy(value, memo))
return y
d[dict] = _deepcopy_dict

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Speed up :func:`copy.deepcopy` of :class:`dict`, :class:`list` and
:class:`tuple` containers whose elements are atomic immutable objects, by
skipping the per-element recursive call for those elements. Patch by Bernát
Gábor.
Loading