Re: lazy properties?

Discussion in 'Python' started by Ian Kelly, Nov 1, 2012.

  1. Ian Kelly

    Ian Kelly Guest

    On Thu, Nov 1, 2012 at 3:38 PM, Andrea Crotti <> 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))
     
    Ian Kelly, Nov 1, 2012
    #1
    1. Advertising

  2. Ian Kelly

    Miki Tebeka Guest

    Miki Tebeka, Nov 1, 2012
    #2
    1. Advertising

  3. Ian Kelly

    Miki Tebeka Guest

    Miki Tebeka, Nov 1, 2012
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ken Pu
    Replies:
    3
    Views:
    674
    Steven D'Aprano
    Jan 16, 2009
  2. Boris Borcic
    Replies:
    0
    Views:
    550
    Boris Borcic
    Jan 16, 2009
  3. Boris Borcic
    Replies:
    0
    Views:
    547
    Boris Borcic
    Jan 16, 2009
  4. Andrea Crotti

    lazy properties?

    Andrea Crotti, Nov 1, 2012, in forum: Python
    Replies:
    0
    Views:
    166
    Andrea Crotti
    Nov 1, 2012
  5. Cameron Simpson

    Re: lazy properties?

    Cameron Simpson, Nov 1, 2012, in forum: Python
    Replies:
    0
    Views:
    192
    Cameron Simpson
    Nov 1, 2012
Loading...

Share This Page