Lazy-Loading/Cached Properties Using Descriptors and Decorators

Comments

5 comments posted
Corrected, Thanks!
Yikes! Thanks for pointing that out. Fixed now -- 'cached_property' maintains an object-keyed dictionary of values.
Posted by Jeet Sukumaran on Sun, 03/21/2010 - 20:16
This could be done with just a descriptor


class Printer(object):
def __get__(self, obj, klass):
if not hasattr(self, '_cached'):
print('calculate...')
self._cached = 'cached'
return self._cached

class MyClass(object):

cached_val = Printer()
# Rest of your code here

I can't see a need to combine a descriptor and a decorator like this... Or am I missing something?

Sorry about the formatting.

Ben

Posted by Anonymous on Mon, 03/22/2010 - 04:26
The Decorator Allows For Multiple Descriptor-Bound Properties

It might be me that is missing something here, but I think what the usage of decorator allows is multiple cached properties without a custom class for each property. For example:

class A(object):
 
    def __init__(self, s):
        self.s = s
 
    @cached_property
    def hello(self):
        return "Hello, %s" % self.s
 
    @cached_property
    def size(self):
        return len(self.s)
 
    @cached_property
    def size_squared(self):
        return len(self.s) ** 2
 
    @cached_property
    def goodbye(self):
        return "Goodbye, %s" % self.s
Posted by Jeet Sukumaran on Mon, 03/22/2010 - 07:58
Don't do that
your cached_property is global (or, a static class member): >>> a = A('world') >>> b = A('moon') >>> a.hello [computing hello] 'Hello, world' >>> b.hello 'Hello, world' >>>
Posted by Anonymous on Sun, 03/21/2010 - 17:32
Thanks, Fixed Now
My earlier reply got stuck in the wrong place. I've fixed the code now, thanks to your comments.
Posted by Jeet Sukumaran on Mon, 03/22/2010 - 08:37

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a biological visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.