initializing mutable class attributes
Alex Martelli
aleaxit at yahoo.com
Thu Sep 2 07:07:59 EDT 2004
Bengt Richter <bokr at oz.net> wrote:
...
> Here's a way to auto-initialize an instance attribute to a mutable via a
class variable
> (that happens to be a descriptor ;-)
>
> >>> class C(object):
> ... class prop(object):
> ... def __get__(self, inst, cls=None):
> ... if inst: return inst.__dict__.setdefault('prop',[])
> ... return self
> ... def __set__(self, inst, value): inst.__dict__['prop'] = value
> ... def __delete__(self, inst): del inst.__dict__['prop']
> ... prop = prop()
> ...
I think it's the most elegant approach so far, except I would further
tweak it as follows:
class auto_initialized(object):
def __init__(self, name, callable, *args, **kwds):
self.data = name, callable, args, kwds
def __get__(self, ints, cls=None):
if inst:
name, callable, args, kwds = self.data
self = inst.__dict__[name] = callable(*args, **kwds)
return self
No __set__ and __del__ warranted, I believe. Use would then be, e.g:
class C(object):
prop = auto_initialized('prop', list)
Pity that the name must be specified, but ah well, that's descriptors'
defects -- they don't get reminded about the name upon __get__ etc.
> Any use to you? (disclaimer: not tested beyond what you see here ;-)
I could use it in the Cookbook, side by side with Dan's "overloading
__new__" idea and my custom metaclass, as various approaches to solving
a 'problem' (if that be one) of "automatically initializing mutable
instance attributes". It would help if you and/or Dan posted these
recipes to ActiveState's online cookbook ASAP (deadline is Sat Sep 5...)
-- I'm allowed to add recipes that didn't show up on the online
cookbook, but that _is_ discouraged... (and posting the recipes myself
isn't much better, either).
Alex
More information about the Python-list
mailing list