On this page
copy
Prev: contextvars | Up: stdlib_module | Next: copyreg
Rel: datetime, zoneinfo, calendar, collections, heapq
Ref: docs.python.org — copy
Tags: #public #python3 #stdlib
Import
import copy
Overview
Generic shallow (copy.copy) and recursive deep (copy.deepcopy) object duplication, plus copy.replace (Python 3.13+) for creating modified copies of immutable objects (dataclasses, namedtuples, datetime). Reach for copy.deepcopy() when you must isolate nested mutable dicts/lists from downstream mutation.
Quick Start
import copy
original = {"tags": ["a", "b"]}
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original["tags"].append("c")
assert shallow["tags"] == ["a", "b", "c"] # shares inner list!
assert deep["tags"] == ["a", "b"] # fully independent
Implementation Walkthrough
1. Customizing Copy Behavior (__copy__, __deepcopy__)
When an object holds non-duplicable resources (like a lock or open handle), override __deepcopy__ to preserve or recreate them safely:
import copy
class Snapshot:
def __init__(self, items: list[int]) -> None:
self.items = items
def __deepcopy__(self, memo: dict[int, object]) -> "Snapshot":
return Snapshot(copy.deepcopy(self.items, memo))
s1 = Snapshot([1, 2])
s2 = copy.deepcopy(s1)
s1.items.append(3)
assert s2.items == [1, 2]
2. Generic copy.replace() (Python 3.13+)
import copy
from datetime import date
d = date(2026, 12, 1)
assert copy.replace(d, day=15) == date(2026, 12, 15)
Gotchas & Boundaries
deepcopy()is significantly slower than explicit construction: For hot loops or known dict/list shapes, manual copying ([row.copy() for row in rows]) is much faster.deepcopy()handles reference cycles automatically via itsmemodictionary, preserving shared internal structure.- Some objects cannot be deep-copied (modules, open files, sockets, locks); customize
__deepcopy__if your class wraps one.
Common Functions
- copy.copy() —
copy(x)— Shallow copy operation on arbitrary Python objects. - copy.deepcopy() —
deepcopy(x, memo=None, _nil=[])— Deep copy operation on arbitrary Python objects. - copy.replace() —
replace(obj, /, **changes)— Return a new object replacing specified fields with new values.
Classes & Objects
- copy.Error —
copy.Errorclass. (Methods:.add_note(),.with_traceback())
Linked from
Related notes
- tuts/python3/stdlib_module/contextvars Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/copyreg Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/calendar Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/collections Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/copy/copy Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/copy/deepcopy Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/copy/Error Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/copy/replace Linked here; shared tags: #stdlib