Skip to content

Commit 34b85ef

Browse files
authored
gh-128118: Speed up copy.copy with fast lookup for atomic and container types (#128119)
1 parent 3480124 commit 34b85ef

File tree

2 files changed

+11
-18
lines changed

2 files changed

+11
-18
lines changed

Lib/copy.py

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -67,13 +67,15 @@ def copy(x):
6767

6868
cls = type(x)
6969

70-
copier = _copy_dispatch.get(cls)
71-
if copier:
72-
return copier(x)
70+
if cls in _copy_atomic_types:
71+
return x
72+
if cls in _copy_builtin_containers:
73+
return cls.copy(x)
74+
7375

7476
if issubclass(cls, type):
7577
# treat it as a regular class:
76-
return _copy_immutable(x)
78+
return x
7779

7880
copier = getattr(cls, "__copy__", None)
7981
if copier is not None:
@@ -98,23 +100,12 @@ def copy(x):
98100
return _reconstruct(x, None, *rv)
99101

100102

101-
_copy_dispatch = d = {}
102-
103-
def _copy_immutable(x):
104-
return x
105-
for t in (types.NoneType, int, float, bool, complex, str, tuple,
103+
_copy_atomic_types = {types.NoneType, int, float, bool, complex, str, tuple,
106104
bytes, frozenset, type, range, slice, property,
107105
types.BuiltinFunctionType, types.EllipsisType,
108106
types.NotImplementedType, types.FunctionType, types.CodeType,
109-
weakref.ref, super):
110-
d[t] = _copy_immutable
111-
112-
d[list] = list.copy
113-
d[dict] = dict.copy
114-
d[set] = set.copy
115-
d[bytearray] = bytearray.copy
116-
117-
del d, t
107+
weakref.ref, super}
108+
_copy_builtin_containers = {list, dict, set, bytearray}
118109

119110
def deepcopy(x, memo=None, _nil=[]):
120111
"""Deep copy operation on arbitrary Python objects.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve performance of :func:`copy.copy` by 30% via
2+
a fast path for atomic types and container types.

0 commit comments

Comments
 (0)