On this page
  1. copy
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Customizing Copy Behavior (__copy__, __deepcopy__)
  7. 2. Generic copy.replace() (Python 3.13+)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

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

Common Functions

Classes & Objects

Linked from

Related notes