## Wednesday, July 24, 2013

### Python object copy

We ran into a problem, which made me puzzled at the beginning. After minutes of debug, I realized I was in the "object reference" trap which I thought would never meet it :(
Here's the simplified code

"set a" changed since 2nd loop while we were expecting it as a consistent value.

From the output we got some information
- memory address of variable delta was re-allocated in every loop -> line#14,18,22
- item we changed 3 times in line #9, but they affected on same object because the id remains same line#15,19,23. And that's why the problem occur.

Analysis result: from the memory address we printed, we found that the object we changed(item, from delta), is no doubt a member in "set a".
The item is a

# object reference

of an element of "set a"

We can created a copy of "delta" instead of reference to "set a", but there're 2 kinds of copy in Python. Shallow copy and deep copy.

# Pseudo code

 Python code Pseudo code a = [1,2] Node** pa=new Node*;pa = new Node(1);pa = new Node(2);pa = new Node*(1,2); reference operation b = ab is a #Trueid(b) == id(a) #Trueid(b) == id(a) #True Node**& pb = pa; //C++ referenceprintf("%p", pa)printf("%p", pb) shallow copy b=list(a)b is a #Falseid(b) == id(a) #Falseid(b) == id(a) #True Node** pb=new Node*;pb = pa;pb = pa;pb = pa; deep copy import copyb = copy.deepcopy(a)id(b) == id(a) #Falseid(b) == id(a) #False Node** pb=new Node*;pb = new Node(pa);pb = new Node(pa);pb = new Node(pa);