views:

202

answers:

2

Recently I've gone through an existing code base and refactored a lot of instance attributes to be lazy, ie. not be initialised in the constructor but only upon first read. These attributes do not change over the lifetime of the instance, but they're a real bottleneck to calculate that first time and only really accessed for special cases.

I find myself typing the following snippet of code over and over again for various attributes across various classes:

class testA(object):

  def __init__(self):
    self._a = None
    self._b = None

  @property
  def a(self):
    if self._a is None:
      # Calculate the attribute now
      self._a = 7
    return self._a

  @property
  def b(self):
    #etc

Is there an existing decorator to do this already in Python that I'm simply unaware of? Or, is there a reasonably simple way to define a decorator that does this?

I'm working under Python 2.5, but 2.6 answers might still be interesting if they are significantly different.

A: 

property is a class. A descriptor to be exact. Simply derive from it and implement the desired behavior.

class lazyproperty(property):
   ....

class testA(object):
   ....
  a = lazyproperty('_a')
  b = lazyproperty('_b')
Ignacio Vazquez-Abrams
+6  A: 

Here is an example implementation of a lazy property decorator which removes the boilerplace:

def lazyprop(fn):
    attr_name = '_lazy_' + fn.__name__
    @property
    def _lazyprop(self):
        if not hasattr(self, attr_name):
            setattr(self, attr_name, fn(self))
        return getattr(self, attr_name)
    return _lazyprop


class Test(object):

    @lazyprop
    def a(self):
        print 'generating "a"'
        return range(5)

Interactive session:

>>> t = Test()
>>> t.__dict__
{}
>>> t.a
generating "a"
[0, 1, 2, 3, 4]
>>> t.__dict__
{'_lazy_a': [0, 1, 2, 3, 4]}
>>> t.a
[0, 1, 2, 3, 4]
Mike Boers
Can someone recommend an appropriate name for the inner function? I'm so bad at naming things in the morning...
Mike Boers
I usually name the inner function the same as the outer function with a preceding underscore. So "_lazyprop" - follows the "internal use only" philosophy of pep 8.
spenthil
This works great :) I don't know why it never occurred to me to use a decorator on a nested function like that, too.
detly
+1: I love decorators!
Adam Paynter