This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: copy.deepcopy() copying pointers from a dict/dict/list, should copy values
Type: behavior Stage:
Components: Extension Modules Versions: Python 2.6
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 2022-04-11 14:57 by admin. 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)
>>> id(bar)
>>> id(foo['a'])
>>> id(bar['a'])
>>> id(foo['b'])
>>> id(bar['b'])
>>> id(foo['b']['c'])
>>> id(bar['b']['c'])
>>> id(foo['b']['c'][0])
>>> id(bar['b']['c'][0])
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
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!
Date User Action Args
2022-04-11 14:57:05adminsetgithub: 53825
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