Choose a shallow or deep copy according to nested mutability.
What You Will Learn
copy.copy() creates a new outer container but retains references to nested elements; copy.deepcopy() recursively copies many nested objects while preserving sharing through memoization. Not all resources can or should be deep-copied.
Implement __copy__ or __deepcopy__ when custom classes need special semantics.
Class interfaces should preserve their stated invariants. Type annotations describe intent but do not enforce runtime types on their own.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
import copy
original_data = {"tasks": ["draft"]}
shallow_copy = copy.copy(original_data)
deep_copy = copy.deepcopy(original_data)
original_data["tasks"].append("review")
print(shallow_copy["tasks"])
print(deep_copy["tasks"])
How the Example Works
- The imports provide the standard-library tools used in the demonstration: copy.
- The variable original_data holds the result of {'tasks': ['draft']}. Later lines use that value or inspect how it changes.
- The variable shallow_copy holds the result of copy.copy(original_data). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
['draft', 'review']
['draft']
When You Would Use This
A class becomes useful when several operations must maintain rules around related data. Think about which state belongs to each instance, which operations should be public, and how errors should be reported. Avoid making the design more complex than the underlying task.
Practice: Modify the Code
Copy a nested list both ways and mutate one inner element.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assuming shallow copies recursively duplicate nested lists and dictionaries.
- Applying deepcopy() indiscriminately to locks, connections, large object graphs, or other resources.
Key Takeaways
- Choose a shallow or deep copy according to nested mutability.
- copy.copy() creates a new outer container but retains references to nested elements; copy.deepcopy() recursively copies many nested objects while preserving sharing through memoization.
- Implement __copy__ or __deepcopy__ when custom classes need special semantics.