How to instantiate in a lazy way?

Nick Craig-Wood nick at craig-wood.com
Tue Dec 2 08:30:45 EST 2008


Slaunger <Slaunger at gmail.com> wrote:
>  On 2 Dec., 11:30, Nick Craig-Wood <n... at craig-wood.com> wrote:
> 
> >
> > For 4 attributes I'd probably go with the __getattr__.
> >
>  OK, I'll do that!
> 
> > Or you could easily write your own decorator to cache the result...
> >
> > Eg http://code.activestate.com/recipes/363602/
> 
>  Cool. I never realized I could write my own decorators!
>  I've so far only used them for
>  @classmethod, @staticmethod and stuff like that.
>  User defined decorators are nice and fun to do as well.
>  I just hope it will be understandable
>  in four years also...

Actually that decorator does exactly what you want.  It replaces the
attribute with the actual data so after the first call there is no
overhead.  I'd use that I think!

> > > ?With the property methology you do the value check on each get, which
> > > ?does not look as "clean". The property methology is also a little less
> > > ?arcane I guess for less experienced Python programmers to understand
> > > ?when re-reading the code.
> >
> > Less magic is how I would put it. ?Magic is fun to write, but a pain
> > to come back to. ?Over the years I find I try to avoid magic more and
> > more in python.
> >
>  Ah, I see. I hope you do not consider user defined decorators
>  "magic" then? ;-)

Well the magic is contained in the decorator so it isn't splattered
throughout your code!

Decorators are part of the meta-programming toolbag along with
metaclasses.  Used sparingly they can be extrememly useful!

>  Again, thank you for your assistance, Nick!

No problem!

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list