Course contentsShow
← Python
Lesson 460 of 1,0607. Object-Oriented ProgrammingFree lesson

Customizing Object Copying Behavior

Implement __copy__ and __deepcopy__ to define how your objects should be duplicated when using the standard library copy module.

In this lesson, you will learn how to take manual control over how your custom objects are duplicated using Python’s copy module.

Why Customize Copying?

When you use copy.copy() or copy.deepcopy() on your objects, Python uses default logic. However, sometimes your object might hold resources—like an open file connection, a network socket, or a temporary cache—that shouldn't be duplicated, or it might require special logic to reconstruct its internal state.

Implementing __copy__ and __deepcopy__

You can define two "magic methods" in your class to intercept the copying process:

  1. __copy__(self): Called by copy.copy(). It should return a shallow copy of your object. A shallow copy creates a new instance but keeps references to the original object's child items.
  2. __deepcopy__(self, memo): Called by copy.deepcopy(). It should return a deep copy (a new instance where all nested objects are also recursively copied). The memo argument is a dictionary used by Python to keep track of objects already copied, preventing infinite loops in circular data structures.

Practical Example

Imagine an Archive class that tracks a unique ID. We want to ensure that every copy gets a new, unique ID instead of sharing the original's identity:

import copy

class Archive:
    def __init__(self, data, archive_id):
        self.data = data
        self.archive_id = archive_id

    def __copy__(self):
        # Create a new instance with the same data, but a new ID
        return Archive(self.data, self.archive_id + "_copy")

    def __deepcopy__(self, memo):
        # Recursively copy data, then apply custom logic
        new_data = copy.deepcopy(self.data, memo)
        return Archive(new_data, self.archive_id + "_deep_copy")

# Usage
orig = Archive(["file1"], "ID_001")
shallow = copy.copy(orig)
print(shallow.archive_id)  # Outputs: ID_001_copy

By defining these methods, you decide exactly how your objects transition into their new existence. If you don't define them, Python will perform a standard attribute-level copy, which may not always be safe or desirable for complex objects.

Key Takeaway: You can customize object duplication by implementing __copy__ for shallow copies and __deepcopy__ for full, recursive copies to ensure your objects maintain their integrity during the cloning process.