How to Make a Shallow Clone of an Object in Python
Demonstrates using copy.copy() to create a shallow clone of a Python object, showing how nested mutable data is shared while top-level attributes are independent.
Python code
27 linesimport copy
class Config:
def __init__(self):
self.settings = {"volume": 50}
self.user = "admin"
def demonstrate_shallow_copy():
original = Config()
shallow = copy.copy(original)
# Mutating nested object is visible in both (shallow copy share it)
shallow.settings["volume"] = 90
print(f"Original settings: {original.settings}")
print(f"Shallow settings: {shallow.settings}")
# Mutating top-level attribute is isolated
shallow.user = "guest"
print(f"Original user: {original.user}")
print(f"Shallow user: {shallow.user}")
if __name__ == "__main__":
demonstrate_shallow_copy()
Output
Original settings: {'volume': 90}
Shallow settings: {'volume': 90}
Original user: admin
Shallow user: guest
How it works
The copy.copy function creates a new object but keeps references to the same nested objects — the settings dictionary is shared between the original and the shallow copy. That's why changing shallow.settings['volume'] also changes original.settings. Top-level attributes like user are independent because copy.copy assigns a new value to that slot in the new object. Use copy.deepcopy when you need nested structures to be fully separate.
Common mistakes
- Forgetting that nested dictionaries or lists are still shared in a shallow copy
- Using `=` instead of `copy.copy`, which doesn't create any new object at all
Variations
- Use `copy.deepcopy` for a fully independent clone
- Use `obj.__copy__()` if a custom copy method is defined
Real-world use cases
- Forks a config object in a Git hook script to preview changes without affecting the main config on disk.
- Clones a mutable dataclass holding session state so background workers can experiment without corrupting the live object.
- Copies a temporary pipeline stage object in a release automation script, so rollback data stays untouched.
Sponsored
More from Git + Python
- Amend Last Commit Message in Python easy
- Bisect Good Bad Automation Script in Python easy
- Build a Simple Log Graph in Python easy
- Bump Semantic Version Git Tag in Python easy
- Count Unique Contributors from Git Shortlog in Python easy
- Create a Mock GitHub Release API in Python for Testing gh CLI easy
Keep learning
Related tutorials and quizzes for this topic.