shallow copy vs. deep copy
Chris Liechti
cliechti at gmx.net
Sat Jun 22 12:42:43 EDT 2002
Uwe Mayer <merkosh at hadiko.de> wrote in
news:MPG.177ec42fc19fcbf598968f at news.rz.uni-karlsruhe.de:
> am am wondering where to draw the line between a shallow copy and a deep
> copy of compound objects.
>
> when creating a shallow copy i could most easily create a new object and
> say
>
> new.__dict__ = old.__dict__
hat way both object have the same namespace, don't they?. thats more like
the Borg pattern (Singleton replacement). if you change an attribute in one
object it will apear in the other object too.
> on the other side i could also:
>
> new.__dict__ = old.__dict__.copy()
that's what i would call a swallow copy.
> which creates a shallow copy of the old instance dictionary.
> if all attributes of the class are primitive (like int, long, string)
...
> also: if i create a deep copy and my instance attributes only contain
> immutable objects there's no difference if i create another copy or just
> pass the reference. if one of the objects attribute gets "changes" it'll
> be reassigned a new object and thats it.
> what's the "fine" way here?
not copying immutable objects is good to save memory, but it might not be
so easy to know if an object is immutable. ok you can check types for
tuples, strings, numbers etc. but you can't do much (at least simple) about
instances of user objects. it might be overkill for a first shoot to
optimize this.
viel spass,
chris
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list