Python copy Module

In this guide, you'll explore Python's copy module, which is used to create shallow and deep copies of objects. Learn its functions and examples for practical use.

The copy module in Python provides functions to create shallow and deep copies of objects. This is useful for duplicating objects without affecting the original instance.

Table of Contents

  1. Introduction
  2. Shallow vs. Deep Copy
  3. Functions in copy
    • copy
    • deepcopy
  4. Copying Custom Objects
    • Implementing __copy__ and __deepcopy__ Methods
  5. Examples
    • Shallow Copying a List
    • Deep Copying a List of Lists
    • Copying Custom Objects
  6. Real-World Use Case
  7. Conclusion
  8. References

Introduction

The copy module provides a way to duplicate objects in Python. It offers two primary functions: copy for shallow copying and deepcopy for deep copying. Understanding the difference between shallow and deep copies is crucial to using this module effectively.

Shallow vs. Deep Copy

Shallow Copy

A shallow copy of an object creates a new object, but inserts references into it to the objects found in the original. In other words, it constructs a new collection object and then populates it with references to the child objects found in the original.

Deep Copy

A deep copy of an object creates a new object and recursively adds copies of the objects found in the original, creating a fully independent clone. This means that changes to the deep-copied object do not affect the original object.

Functions in copy

copy

The copy function creates a shallow copy of an object.

import copy

original = [1, 2, [3, 4]]
shallow_copy = copy.copy(original)
print(shallow_copy)

Output:

[1, 2, [3, 4]]

deepcopy

The deepcopy function creates a deep copy of an object.

import copy

original = [1, 2, [3, 4]]
deep_copy = copy.deepcopy(original)
print(deep_copy)

Output:

[1, 2, [3, 4]]

Copying Custom Objects

Implementing __copy__ and __deepcopy__ Methods

For custom objects, you can control how they are copied by implementing the __copy__ and __deepcopy__ methods.

import copy

class MyClass:
    def __init__(self, value):
        self.value = value

    def __copy__(self):
        print("Performing shallow copy")
        return MyClass(self.value)

    def __deepcopy__(self, memo):
        print("Performing deep copy")
        return MyClass(copy.deepcopy(self.value, memo))

obj = MyClass(10)
shallow_copy = copy.copy(obj)
deep_copy = copy.deepcopy(obj)

Output:

Performing shallow copy
Performing deep copy

Examples

Shallow Copying a List

Create a shallow copy of a list.

import copy

original = [1, 2, 3, [4, 5]]
shallow_copy = copy.copy(original)
shallow_copy[3][0] = 99
print("Original:", original)
print("Shallow Copy:", shallow_copy)

Output:

Original: [1, 2, 3, [99, 5]]
Shallow Copy: [1, 2, 3, [99, 5]]

Deep Copying a List of Lists

Create a deep copy of a list of lists.

import copy

original = [1, 2, 3, [4, 5]]
deep_copy = copy.deepcopy(original)
deep_copy[3][0] = 99
print("Original:", original)
print("Deep Copy:", deep_copy)

Output:

Original: [1, 2, 3, [4, 5]]
Deep Copy: [1, 2, 3, [99, 5]]

Copying Custom Objects

Copy a custom object using shallow and deep copy.

import copy

class MyClass:
    def __init__(self, value):
        self.value = value

    def __repr__(self):
        return f"MyClass(value={self.value})"

obj = MyClass([1, 2, 3])
shallow_copy = copy.copy(obj)
deep_copy = copy.deepcopy(obj)

shallow_copy.value[0] = 99
deep_copy.value[1] = 42

print("Original:", obj)
print("Shallow Copy:", shallow_copy)
print("Deep Copy:", deep_copy)

Output:

Original: MyClass(value=[99, 2, 3])
Shallow Copy: MyClass(value=[99, 2, 3])
Deep Copy: MyClass(value=[1, 42, 3])

Real-World Use Case

Configuration Management

When working with configurations, it is often necessary to duplicate configuration objects to modify and test without affecting the original configuration.

import copy

class Config:
    def __init__(self, settings):
        self.settings = settings

default_config = Config({'setting1': True, 'setting2': False})
test_config = copy.deepcopy(default_config)
test_config.settings['setting1'] = False

print("Default Config:", default_config.settings)
print("Test Config:", test_config.settings)

Output:

Default Config: {'setting1': True, 'setting2': False}
Test Config: {'setting1': False, 'setting2': False}

Conclusion

The copy module in Python provides essential tools for duplicating objects through shallow and deep copies. Understanding the differences between shallow and deep copies helps in choosing the right method for various use cases, ensuring that changes to copied objects do not undesirably affect the original objects.

References

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare