classification
Title: copy.deepcopy() copying pointers from a dict/dict/list, should copy values
Type: behavior Stage:
Components: Extension Modules Versions: Python 2.6
process
Status: closed Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: loewis, nharkins
Priority: normal Keywords:

Created on 2010-08-15 20:12 by nharkins, last changed 2010-08-15 22:19 by nharkins. This issue is now closed.

Messages (5)
msg114007 - (view) Author: Neil Harkins (nharkins) Date: 2010-08-15 20:12
hi. after using deepcopy() on a nested dict/list structure, 
i noticed that modifications to the deepcopied structure were 
affecting the original. this looks to me like a serious bug:

>>> import copy
>>> foo = { 'a':[1,2,3], 'b':{'c':[4,5]} }
>>> bar = copy.deepcopy(foo)
>>> id(foo)
4297360512
>>> id(bar)
4297373104
>>> id(foo['a'])
4299410752
>>> id(bar['a'])
4299760200
>>> id(foo['b'])
4297371984
>>> id(bar['b'])
4297373920
>>> id(foo['b']['c'])
4299721040
>>> id(bar['b']['c'])
4299761496
>>> id(foo['b']['c'][0])
4297074656
>>> id(bar['b']['c'][0])
4297074656
msg114008 - (view) Author: Martin v. Löwis (loewis) * (Python committer) Date: 2010-08-15 20:20
Why do you say "modifications to the deepcopied structure were 
affecting the original"? Your code sample doesn't include any modifications to the deepcopied structure.

Try modifying it, and watch the original remaining unchanged.
msg114009 - (view) Author: Neil Harkins (nharkins) Date: 2010-08-15 20:45
thanks for the quick response. 

that was just my working up a simplified repro, but you are 
correct: on modification there, it gets a new id() location.

totally not what i would've expected (python flags
it for copying when it changes, to save space?)

however i am still seeing the problem in my code, so
i will continue to whittle it down to a simpler repro,
and hopefully add it here later today.
msg114010 - (view) Author: Martin v. Löwis (loewis) * (Python committer) Date: 2010-08-15 20:51
Numbers are immutable, and hence don't need to be copied. In fact, it is impossible to create two int object that both have the value 4, but are different objects:

py> 2+2 is 3+1
True
msg114016 - (view) Author: Neil Harkins (nharkins) Date: 2010-08-15 22:19
learn something everyday. i have found the bug in my code, 
deepcopy() is not to blame. thx for your time!
History
Date User Action Args
2010-08-15 22:19:15nharkinssetstatus: open -> closed

messages: + msg114016
2010-08-15 20:51:02loewissetmessages: + msg114010
2010-08-15 20:45:04nharkinssetmessages: + msg114009
2010-08-15 20:20:41loewissetnosy: + loewis
messages: + msg114008
2010-08-15 20:12:24nharkinscreate