[Tutor] Re: Re: copies deep and shallow

Marilyn Davis marilyn at deliberate.com
Mon Feb 16 14:07:33 EST 2004


Thank you Andrei,

[snip]

> Why would you use a (very slow) deepcopy when it doesn't offer any extra
> functionality? I can't modify integers/strings/tuples in-place, so I can't

I see.  So deepcopy is slow, even for shallow objects?

> accidentally change g by changing something in h. If I'd just used a
> reference, the result would have been this (g is modified as well):
> 
> >>> h = g
> >>> h[0] = 2
> >>> g, h
> ({0: 2, 2: 3, 4: 5}, {0: 2, 2: 3, 4: 5})
> 
> I use references e.g. when I read items from some nested dictionary. E.g.
> if I have a nested dictionary and I'm interested in keys inside
> data["feeds"][0]["items"][0].keys(), I'll probably just do this:
> 
> item = data["feeds"][0]["items"][0]
> item["somekey"] = newvalue
> item["otherkey"] = othervalue

I see.  Good idea.

> 
> I *want* the original dictionary in data["feeds"][0]["items"][0] to be
> changed, so obviously I won't do a copy - the item=... assignment is only
> meant to add some clarity to the code and save me some typing. 
> If I meant to change that particular item but did not want the changes to
> go back in the nested dictionary I'd have used copy (if the dictionary only
> contains immutable values) or deepcopy (if it contains mutable values).

Got it.

> 
> But generally speaking you can ignore copy if you wish and write perfectly
> reasonable applications without even knowing it exists :). But then again,

Yes.  This is what I was thinking.

> you can also ignore deepcopy if you wish, or dictionaries all together
> (there are plenty of languages without a dictionary type) or...

But, I'm teaching a python class!  I have to deep-understand everything.

And I love the dictionary type.  So much is done for free.

> 
> Oh, and I should point out that the docs mention two possible gotchas of
> deepcopy (in paragraph 3.18):
> - Recursive objects (compound objects that, directly or indirectly, contain
> a reference to themselves) may cause a recursive loop. 
> - Because deep copy copies everything it may copy too much, e.g.,
> administrative data structures that should be shared even between copies. 

Yes, but it also says it cleverly solves these problems.

OK.  Thank you very much.  I think I get it.  I hope I get all there
is to get.

I'm very grateful that you have taken the time to explain all this.

Marilyn




More information about the Tutor mailing list