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




