Preface
deepcopy is from the Python standard librarycopy
A function provided by the module that is used to create objectsDeep copy。
The difference between deep copy and shallow copy is thatDeep copyRecursively copying objects and all objects they contain, while shallow copies are onlyCopy the object itself, without recursively copying child objects inside the object.
Specifically,
deepcopy
A new object will be created.And make sure that each element in the new object is an independent copy of the element in the original object,Deeply copy the entire object structure。
1. The difference between shallow copy and deep copy
shallow copy: Copy the object itself, but for mutable objects within the object (such as lists, dictionaries, etc.), they still point toThe same location in the original object. That is, the copied object is a copy of the "first layer" of the original object, and for nested mutable objects,The shallow copy just references them。
Deep copy: Copy objects and their nested objects to ensure that all hierarchies are independent. That is, deep copy recursively copies objects and all their sub-objects.
2. Usage of deepcopy
import copy # Example: Using deepcopyoriginal = {'a': 1, 'b': [2, 3], 'c': {'d': 4}} # Create a deep copy of the original objectdeep_copied = (original) # Modify the content of the deep copy without affecting the original objectdeep_copied['b'][0] = 100 deep_copied['c']['d'] = 200 print("Original:", original) print("Deep Copied:", deep_copied)
Output:
Original: {'a': 1, 'b': [2, 3], 'c': {'d': 4}} Deep Copied: {'a': 1, 'b': [100, 3], 'c': {'d': 200}}
explain:
-
original
is a dictionary containing nested dictionaries and lists. -
deepcopy
Createdoriginal
A new copy of the object, includingoriginal
A separate copy of all nested structures (lists and dictionaries) in it. - Revise
deep_copied
Inb
List andc
The value of the dictionary will not affect the original object.original
, because they are already completely independent objects.
3. Comparison between shallow copy and deep copy
We can further understand the difference between shallow copy and deep copy through the following examples:
import copy # Sample object: a dictionary containing mutable objectsoriginal = {'a': 1, 'b': [2, 3], 'c': {'d': 4}} # Create a shallow copyshallow_copied = (original) # Modify the internal structure of the shallow copyshallow_copied['b'][0] = 100 shallow_copied['c']['d'] = 200 print("Original:", original) print("Shallow Copied:", shallow_copied)
Output:
Original: {'a': 1, 'b': [100, 3], 'c': {'d': 200}} Shallow Copied: {'a': 1, 'b': [100, 3], 'c': {'d': 200}}
explain:
-
shallow_copied
It is created through shallow copy,b
List andc
The dictionary still points tooriginal
The same object in , so modifyshallow_copied
Internalb
andc
It will also affectoriginal
。 - Unlike deep copy, it recursively copies all object structures, avoiding this.
4. Why use deepcopy?
Avoid accidental modification of original objects: If the object is nested (such as containing mutable types such as lists, dictionaries, etc.), using shallow copy may cause the original object to be accidentally modified when modifying the deep object.
deepcopy
This can be ensured that all hierarchies are copied independently, avoiding this situation.Independent copy: In some scenarios, you need to modify an object, but you also want to keep the original object unaffected. use
deepcopy
It can be ensured that a completely separate copy is created.
5. The working principle of deepcopy
deepcopy
In fact, it will recursively traverse all levels of the object and copy each element. For built-in types (such as lists, dictionaries, collections, etc.), it will decide how to copy based on the type of the object. If the object contains a custom class or object,deepcopy
Will be based on the class__deepcopy__
Method to handle.
If the object is of immutable type (such as numbers, strings, tuples, etc.),deepcopy
The object itself will be returned directly, because they are immutable in themselves.
6. __deepcopy__ Method
For some custom objects, you can implement__deepcopy__
Methods to define the deep copy behavior of an object. This method will bedeepcopy
is automatically called.
import copy class MyClass: def __init__(self, value): = value def __deepcopy__(self, memo): # Customize deep copy logic new_obj = MyClass() print(f"Deep copying MyClass with value {}") return new_obj # Create a MyClass objectobj = MyClass(42) # Deep copy of MyClass objectobj_copy = (obj)
Output:
Deep copying MyClass with value 42
explain:
-
__deepcopy__
Methods allow you to customize the behavior of objects during deep copying. In this example, we customizeMyClass
of__deepcopy__
Method to create a newMyClass
Object and print out the deep copy of the relevant information.
7. Things to note when using deepcopy
Performance overhead:
deepcopy
Recursively copy all levels of an object, so for complex data structures containing a large number of nested objects, usedeepcopy
It may bring greater performance overhead. In situations where performance requirements are high, it is best to avoid unnecessary deep copies.Quote count:
deepcopy
A new copy of all nested objects is created, so there is no shared part between the original object and the copy object. If there are a large number of objects that need to be copied, it may cause a large memory consumption.Recycle reference:
deepcopy
Can be processed by recycled references (i.e., mutual references between objects) through amemo
Dictionary to ensure that each object will be copied only once.
Summarize
deepcopy
It is a tool for creating completely independent copies of objects, especially suitable for scenarios where complex data structures (such as containing nested lists, dictionaries and other variable objects).
Unlike shallow copies, deep copies recursively copy objects and all their nested elements, ensuring there is no shared part between the original object and the copy.
In scenarios where complex objects are processed or where a completely independent copy is required,
deepcopy
It is a very useful tool.
This is the article about the usage and precautions of deepcopy in Python. For more detailed explanations of deepcopy, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!