Object Cloning in Python

Clone objects using the copy module (shallow and deep copy).

IntermediateObject-Oriented ProgramsExample 19 of 25
object-cloning.py
Run in browser
1# Program to demonstrate object cloning
2
3import copy
4
5class Node:
6 def __init__(self, value, next=None):
7 self.value = value
8 self.next = next
9
10n1 = Node(1, Node(2))
11shallow = copy.copy(n1)
12deep = copy.deepcopy(n1)
13
14print("Original next:", n1.next)
15print("Shallow next:", shallow.next)
16print("Deep next:", deep.next)

Output

Original next: <__main__.Node object at ...>
Shallow next: <__main__.Node object at ...>
Deep next: <__main__.Node object at ...>

What's going on

copy.copy shares nested objects, while copy.deepcopy clones the entire object graph.