3

Time to time I need to deepcopy an object and sometimes it's a dictionary object so I use ** operator to copy it easily but I always wondered if deepcopy is any different or efficient in some sense. Which one is more efficient in terms of memory footprint, cpu time and does deepcopy iterate over like ** operator does?

import copy
myObj = {"some": "data", "to": "copy"}

# With using unpacking operator.
newObj1 = {**myObj}

# With using `copy.deepcopy` function.
newObj2 = copy.deepcopy(myObj)
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
Guven Degirmenci
  • 684
  • 7
  • 16

1 Answers1

3

Be careful; there's a big difference when those dictionary values are mutable, and ** does not behave equivalently to copy.deepcopy():

>>> import copy
>>> myObj = {"some": "data", "to": ["copy", "this"]}
>>> newObj1 = {**myObj}
>>> newObj2 = copy.deepcopy(myObj)
>>> myObj["to"][1] = "that"
>>> newObj1
{'some': 'data', 'to': ['copy', 'that']}
>>> newObj2
{'some': 'data', 'to': ['copy', 'this']}

As shown in PEP 448, using ** iterable unpacking is more akin to dict.copy() than copy.deepcopy().

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235