Python dictionary deepcopy

mandel picture mandel · May 8, 2009 · Viewed 27.3k times · Source

I was wondering in how does exactly deepcopy work in the following context:

from copy import deepcopy

def copyExample:
    self.myDict = {}
    firstPosition = "First"
    firstPositionContent = ["first", "primero"]
    secondPosition = "Second"
    secondPositionContent = ["second"]
    self.myDict[firstPosition] = firstPositionContent 
    self.myDict[secondPosition] = secondPositionContent
    return deepcopy(self.myDict)

def addExample(self):
    copy =  self.copyExample()
    copy["Second"].add("segundo")

Does it return the reference to the lists I have in the dictionary? Or does it work as I expect and copy every list in a new list with a different reference?

I know what a deep copy is (so there is no need to explain the difference between deep and shallow) but I am wondering if it works as I expect it to do and therefore do not change the instance variable when I use addExample().

Answer

Bjorn picture Bjorn · May 8, 2009

The documentation makes it pretty clear that you're getting new copies, not references. Deepcopy creates deep copies for built in types, with various exceptions and that you can add custom copy operations to your user-defined objects to get deep copy support for them as well. If you're not sure, well that's what unit testing is for.