[Tutor] question about __copy__ and __deepcopy__

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Apr 14 16:34:39 EDT 2016


On 14 April 2016 at 20:38, Albert-Jan Roskam <sjeik_appie at hotmail.com> wrote:
> Hi,
>
> Lately I have been using the "mutable namedtuple"  shown below a lot. I found it somewhere on StackOverflow or ActiveState or something.
> In its original form, it only had an __init__ method.

I don't know about your copy/deepcopy stuff. It looked fine to me but
I'm not very experienced in that area. I wonder what this mutable
namedtuple is for though.

Looking at it:

> class Record(dict):
>
>     def __init__(self, *args, **kwargs):
>         super(Record, self).__init__(*args, **kwargs)
>         self.__dict__ = self

It's not so much a mutable namedtuple as an "attribute dict". It's a
dict whose keys can be accessed as attributes - because it is its own
instance dict. Of course it also has dict attributes like pop, items
etc. (see dir(dict) for a list). The reason that dicts use d[k] rather
than d.k for accessing keys is to be able to store arbitrary keys
without conflicting with the dict's methods which are attributes.

A namedtuple is something very different. It subclasses tuple and the
whole idea is that an instance is lightweight (not having an attribute
dict) and hashable and imutable etc. A mutable version of that might
just look like:

class Point(object):
    # No instance dict:
     __slots__ = ['x', 'y']

    def __init__(self, x, y):
        self.x = x
        self.y = y

It depends what you really want it for though.

--
Oscar


More information about the Tutor mailing list