Object copying itself

Alex Martelli aleax at aleax.it
Mon Feb 18 12:12:34 CET 2002


Quinn Dunkan wrote:
        ...
>>I want object references copied (shallow copy) but the lists need to
>>be copied entirely (deep copy).
        ...
> Note that 'self.__dict__.update(other.__dict__)' is a popular pydiom, but
> that won't deepcopy the lists.

No, but following that with a specific and explicit deepcopying of
the lists looks like a good, clear way to signal this extremely
peculiar design intent that the OP has asserted.  Specific
assignments if the list-attributes' name are know, else a loop, i.e.:

    self.__dict__.update(other.__dict__)
    self.alist = copy.deepcopy(self.alist)
    self.anotherlist = copy.deepcopy(self.anotherlist)

or (with a couple of 2.2'isms) if e.g. you want to get this from
a mixin class or generic function (useful if you need the same
peculiar functionality for more than one object type!):

    self.__dict__.update(other.__dict__)
    for k, v in self.__dict__.iteritems():
        if isinstance(v, list):
            setattr(self, k, copy.deepcopy(v))


This doesn't work for objects with __slots__ (again, in 2.2), but,
there, it's even easier to "loop over all the slots" after all.

Hmmm, come to think of it, one typically does need to "loop over
all instance-specific attributes, be they slots or else keys
in self.__dict__" -- a good abstraction to hide away in a helper
function such as:

def attributeNames(obj):
    try: return obj.__slots__
    except AttributeError: return obj.__dict__.keys()

(not worth using iterators for the small number of attributes
that typically exist...).  Maybe inspect already has that (I
haven't memorized inspect yet:-)... but compatibility with 2.x
for x<2 suggests coding this small helper out anyway...


Alex





More information about the Python-list mailing list