Object copying itself

Quinn Dunkan quinn at regurgitate.ugcs.caltech.edu
Fri Feb 15 21:23:01 EST 2002

On Fri, 15 Feb 2002 18:58:05 +0000, Dale Strickland-Clark
<dale at riverhall.NOTHANKS.co.uk> wrote:
>I have an object which is just data and an __init__ to set up some
>Now I need to allow __init__ to get the defaults from another instance
>of itself if passed as an argument.
>Most of the values are simple numerics and a few object references but
>there are also a couple of lists. 
>I want object references copied (shallow copy) but the lists need to
>be copied entirely (deep copy).
>Do I have to do this by hand or is there a neat way of doing it?

Well, if you really have a lot of attributes, you could futz around with

import copy
from types import *
class Foo:
    def __init__(self, default=None):
        if default is None:
            for k, v in default.__dict__.items():
                if hasattr(v, '__getitem__') or v in (ListType, TupleTyple):
                    nv = copy.deepcopy(v)
                    nv = v
                setattr(self, k, v)

I'd be more inclined to just write out a bunch of assignments, though.  Note
that 'self.__dict__.update(other.__dict__)' is a popular pydiom, but that won't
deepcopy the lists.

More information about the Python-list mailing list