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.

Easy Python 3.9+ Aug 9, 2026 Git + Python 14 views 0 copies

Python code

27 lines
Python 3.9+
import 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

stdout
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

  1. Use `copy.deepcopy` for a fully independent clone
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Git + Python

Related tutorials and quizzes for this topic.