initializing mutable class attributes

Dan Perl dperl at rogers.com
Thu Sep 2 17:50:12 EDT 2004


I really like this one.  I think this 'defaultvalue' class even deserves to
be added as a builtin.  It can even be changed to initialize non-empty
sequences.  And I haven't tried that yet, but it should be able to
initialize an attribute with any kind of object that can be constructed with
no arguments.  Too bad it works only for instance attributes in a class.

I will be a good Pythoneer/Pythonista and I will invoke parent __init__'s
whenever using a library.  My concern was not as a library user, but as a
library developer.  In which case I don't like the idea of relying on users
to be good Python coders.

Dan

"Shalabh Chaturvedi" <shalabh at cafepy.com> wrote in message
news:mailman.2776.1094145516.5135.python-list at python.org...
> Dan Perl wrote:
>
> > Someone else (Shalabh) suggested descriptors for the same problem but I
> > didn't get to consider such a solution until now.
>
> This is what I had in mind:
>
> ---->8-----
> class defaultvalue(object):  # this is a descriptor
>     def __init__(self, name, factory):
>        self.name = name
>        self.factory = factory
>
>     def __get__(self, obj, cls=None):
>        if obj is None:
>           return self
>
>        val = self.factory()
>        setattr(obj, self.name, val)
>        return val
>
>
> class C(object):
>     i = defaultvalue('i',dict)
>     j = defaultvalue('j',list)
>
> c = C()
> print c.i, c.j   # prints {} []
> ---->8-----
>
> Once it has kicked in, it's free of the descriptor overhead. Note you
> only need to define defaultvalue once and reuse it everywhere. Also you
> can give it a function or lambda like:
>
>     k = defaultvalue('k', lambda :[1,2,3])
>
> I still suggest you be a good Pythoneer and use __init__() like everyone
> else. It's a useful habit of always calling the base class __init__() at
> the top of your __init__(). If you don't develop this habit (or of at
> least checking the base for __init__), you will waste debugging cycles
> when you use other libraries.
>
> --
> Shalabh
>
>
>
>
>
>
>





More information about the Python-list mailing list