Object copying itself

xtian xtian at toysinabag.com
Mon Feb 18 16:05:48 EST 2002


Dale Strickland-Clark <dale at riverhall.NOTHANKS.co.uk> wrote in message news:<27mq6ug68esgsh7in71scb9m30phojjf3g at 4ax.com>...

> I want object references copied (shallow copy) but the lists need to
> be copied entirely (deep copy).

It sounds like you may have your terminology confused. Copying an
object reference is not a shallow copy - it's not a copy at all
(except in a degenerate sense), because the references, while copies
of each other, still point to the same object.

If you've called copying a list a deep copy to contrast with the
non-copy of the objects, then you probably mean shallow copy. This is
a copy, because a new list is created, but then all of the list's
items are *non-copied* into it.

This seems to make more sense to me. If it's actually what you want,
then this should implement it:

def copyObj(obj):
	newObj = obj.__class__()
	for name, val in obj.__dict__.iteritems():
		if type(val) is list:
			val = copy.copy(val)
		setattr(newObj, name, val)
	return newObj

This uses some 2.2isms, and doesn't take care of __init__ processing
(that'll depend on how it should be handled in your app), and doesn't
do __slots__ (Alex has discussed how they could be handled).

And I may have misunderstood what you wanted, so it could also be
completely wrong! That's enough disclaimers for today.

Hope it helps...
xtian

(The snipers are passed out in the bushes again.)



More information about the Python-list mailing list