Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #32573

Re: lazy properties?

References <5092EBED.2090002@gmail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2012-11-01 15:52 -0600
Subject Re: lazy properties?
Newsgroups comp.lang.python
Message-ID <mailman.3168.1351806771.27098.python-list@python.org> (permalink)

Show all headers | View raw


On Thu, Nov 1, 2012 at 3:38 PM, Andrea Crotti <andrea.crotti.0@gmail.com> wrote:
> What I would like to write is
>     @lazy_property
>     def var_lazy(self):
>         return long_computation()
>
> and this should imply that the long_computation is called only once..

If you're using Python 3.2+, then functools.lru_cache probably
suffices for your needs.

@property
@functools.lru_cache()
def var_lazy(self):
    return long_computation()

If you really need to shorten that to a single declaration:

def lazy_property(func):
    return property(functools.lru_cache()(func))

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: lazy properties? Ian Kelly <ian.g.kelly@gmail.com> - 2012-11-01 15:52 -0600
  Re: lazy properties? Miki Tebeka <miki.tebeka@gmail.com> - 2012-11-01 16:30 -0700
  Re: lazy properties? Miki Tebeka <miki.tebeka@gmail.com> - 2012-11-01 16:30 -0700

csiph-web