initializing mutable class attributes

Shalabh Chaturvedi shalabh at
Thu Sep 2 19:20:08 CEST 2004

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:

class defaultvalue(object):  # this is a descriptor
    def __init__(self, name, factory): = name
       self.factory = factory

    def __get__(self, obj, cls=None):
       if obj is None:
          return self

       val = self.factory()
       setattr(obj,, val)
       return val

class C(object):
    i = defaultvalue('i',dict)
    j = defaultvalue('j',list)

c = C()
print c.i, c.j   # prints {} []

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.


More information about the Python-list mailing list