8

my Python class has some variables that require work to calculate the first time they are called. Subsequent calls should just return the precomputed value.

I don't want to waste time doing this work unless they are actually needed by the user. So is there a clean Pythonic way to implement this use case?

My initial thought was to use property() to call a function the first time and then override the variable:

class myclass(object):
    def get_age(self):
        self.age = 21 # raise an AttributeError here
        return self.age

    age = property(get_age)

Thanks

hoju
  • 28,392
  • 37
  • 134
  • 178
  • 2
    Are you asking about memoization? http://en.wikipedia.org/wiki/Memoization. This is pretty common OO design pattern. – S.Lott Oct 21 '09 at 02:05

5 Answers5

15
class myclass(object):
    def __init__(self):
        self.__age=None
    @property
    def age(self):
        if self.__age is None:
            self.__age=21  #This can be a long computation
        return self.__age

Alex mentioned you can use __getattr__, this is how it works

class myclass(object):
    def __getattr__(self, attr):
        if attr=="age":
            self.age=21   #This can be a long computation
        return super(myclass, self).__getattribute__(attr)

__getattr__() is invoked when the attribute doesn't exist on the object, ie. the first time you try to access age. Every time after, age exists so __getattr__ doesn't get called

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • 1
    the call to `return getattr(self, attr)` would cause an infinite loop if attr doesn't exist. Use `return super(MyClass, self).__getattr__(attr)` instead. – nosklo Oct 21 '09 at 02:31
  • No doubt __getattr__ should return self.age if attr=='age', rather than calling super's __getattr__. – unutbu Oct 22 '09 at 20:53
  • @~unutbu, The `super.__getattr__` does return `self.age` once it has been created – John La Rooy Oct 22 '09 at 21:03
  • print(myclass().age) returns AttributeError: 'super' object has no attribute '__getattr__'. Am I missing something? – unutbu Oct 22 '09 at 21:15
  • @~unutbu, I had `MyClass` instead of `myclass` also. oops. It's fixed now – John La Rooy Oct 22 '09 at 21:57
6

property, as you've seen, will not let you override it. You need to use a slightly different approach, such as:

class myclass(object):

    @property
    def age(self):
      if not hasattr(self, '_age'):
        self._age = self._big_long_computation()
      return self._age

There are other approaches, such as __getattr__ or a custom descriptor class, but this one is simpler!-)

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
5

Here is decorator from Python Cookbook for this problem:

class CachedAttribute(object):
    ''' Computes attribute value and caches it in the instance. '''
    def __init__(self, method, name=None):
        # record the unbound-method and the name
        self.method = method
        self.name = name or method.__name__
    def __get__(self, inst, cls):
        if inst is None:
            # instance attribute accessed on class, return self
            return self
        # compute, cache and return the instance's attribute value
        result = self.method(inst)
        setattr(inst, self.name, result)
        return result
Denis Otkidach
  • 32,032
  • 8
  • 79
  • 100
2

Yes you can use properties, though lazy evaluation is also often accomplished using descriptors, see e.g:

http://blog.pythonisito.com/2008/08/lazy-descriptors.html

oggy
  • 3,483
  • 1
  • 20
  • 24
1

This question is already 11 years old, and python 3.8 and above now come with cached_property, which perfectly serves this purpose. The property will be computed only once, then kept in memory for subsequent use.

Here is how to use it in this case:

class myclass(object):
    @cached_property
    def age(self):
        return 21  #This can be a long computation
LemmeTestThat
  • 498
  • 7
  • 17