Postpone creation of attributes until needed
Frank Millman
frank at chagford.com
Mon Jun 11 11:33:32 EDT 2007
On Jun 11, 5:22 pm, George Sakkis <george.sak... at gmail.com> wrote:
> On Jun 11, 10:37 am, Frank Millman <f... at chagford.com> wrote:
>
>
> You never *need* decorators, in the sense it's just syntax sugar for
> things you might do without them, but they're handy once you get your
> head around them.
>
> > Actually I did spend a bit of time trying to understand it before
> > posting, and I have a question.
>
> > It seems that this is now a 'read-only' attribute, whose value is
> > computed by the function the first time, and after that cannot be
> > changed. It would probably suffice for my needs, but how easy would it
> > be to convert it to read/write?
>
> It's straightforward, just define a setter wrapper and pass it in the
> property along with the getter:
>
> def cachedproperty(func):
> name = '__' + func.__name__
> def getter(self):
> try: return getattr(self, name)
> except AttributeError: # raised only the first time
> value = func(self)
> setattr(self, name, value)
> return value
> def setter(self, value):
> setattr(self, name, value)
> return property(getter,setter)
>
Wonderful - this is very educational for me :-)
Thanks very much
Frank
More information about the Python-list
mailing list