liveBook · Manning

Deep copy

As explained in Python How-To

A deep copy is a copied object whose interior objects are recursively copied so that mutable objects are not shared with the original.

A deep copy creates a distinct outer object and recursively copies its interior objects, preventing mutable data such as lists, dictionaries, or sets from being shared with the original. section 10.3.2 section 10.3.4

Use deepcopy from Python’s copy module when editing a copied object must leave the original unchanged. Unlike copy, it gives each interior mutable object its own copy. section 10.3.3 section 10.3.4

Editing a copied task safely

A task has a mutable tags list. After deepcopy(task), appending "red" to task_deepcopied.tags changes only the copied task; task retains ["school", "urgent"]. section 10.3.3

Choose the copying strategy according to whether interior mutable objects may be shared:

  • Use a shallow copy when shared interior containers are acceptable or memory savings matter. section 10.3.4
  • Use a deep copy when the copied data must be independently editable. section 10.3.3
  • Customize copying with __copy__ or __deepcopy__ when a class needs instance-specific behavior. section 10.3.5
from copy import deepcopy

task = Task("Homework", "Math and physics", ["school", "urgent"])

task_deepcopied = deepcopy(task)

print(task_deepcopied)
# output: Task('Homework', 'Math and physics', ['school', 'urgent'])

Shows the standard deepcopy call and the copied task before its mutable tags list is changed. section 10.3.3

task_deepcopied.tags.append("red")

print(task_deepcopied)
# output: Task('Homework', 'Math and physics', ['school', 'urgent', 'red'])

print(task)
# output: Task('Homework', 'Math and physics', ['school', 'urgent'])

Demonstrates that changing the copied tags list does not change the original task. section 10.3.3

How Python How-To covers it

How deep it goes
Explains recursive copying through mutable task tags and contrasts it with shallow copying, while deferring customized behavior to a challenge.
Examples
Uses a Task object whose copied tags list gains "red" while the original tags remain unchanged.
What it assumes
Assumes familiarity with shallow copying and mutable data containers such as lists, dictionaries, and sets.
What you can do after
Apply it via copy.deepcopy to create independently editable object graphs.
How it connects
Connects deep copy to shallow copy, mutable objects, the copy module, and __deepcopy__ customization.

Also explained in

Compare how 5 books explain deep copy →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.