diff --git a/Lib/copy.py b/Lib/copy.py index 7a1907d75494d7..a476270d687005 100644 --- a/Lib/copy.py +++ b/Lib/copy.py @@ -126,10 +126,13 @@ def deepcopy(x, memo=None, _nil=[]): if cls in _atomic_types: return x - d = id(x) if memo is None: + if cls in _builtin_iterables and not x: + return cls() + d = id(x) memo = {} else: + d = id(x) y = memo.get(d, _nil) if y is not _nil: return y @@ -173,6 +176,7 @@ def deepcopy(x, memo=None, _nil=[]): _atomic_types = {types.NoneType, types.EllipsisType, types.NotImplementedType, int, float, bool, complex, bytes, str, types.CodeType, type, range, types.BuiltinFunctionType, types.FunctionType, weakref.ref, property} +_builtin_iterables = {tuple, list, dict, set, frozenset} _deepcopy_dispatch = d = {} diff --git a/Misc/NEWS.d/next/Library/2024-07-01-00-32-33.gh-issue-121192.RZFhQP.rst b/Misc/NEWS.d/next/Library/2024-07-01-00-32-33.gh-issue-121192.RZFhQP.rst new file mode 100644 index 00000000000000..d5437172c8dd10 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-07-01-00-32-33.gh-issue-121192.RZFhQP.rst @@ -0,0 +1,2 @@ +Add fast path to :func:`copy.deepcopy` for empty lists, tuples, dicts, sets +or frozensets.