Thursday, November 15, 2012

Lazy Attribute in Python

A lazy attribute is an attribute that is calculated on demand and only once. Here we will see how you can use lazy attribute in your Python class. Setup environment before you proceed:
$ virtualenv env
$ env/bin/pip install wheezy.core
Let assume we need an attribute that is display name of some person Place the following code snippet into some file and run it:
from wheezy.core.descriptors import attribute

class Person(object):
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name
        self.calls_count = 0
        
    @attribute
    def display_name(self):
        self.calls_count += 1
        return '%s %s' % (self.first_name, self.last_name)

if __name__ == '__main__':
    p = Person('John', 'Smith')
    print(p.display_name)
    print(p.display_name)
    assert 1 == p.calls_count
Notice display_name function is decorated with @attribute. The first call promotes function to attribute with the same name. The source is here.

2 comments :

  1. Welcome to @reify

    https://github.com/Pylons/pyramid/blob/master/pyramid/decorator.py

    ReplyDelete
    Replies
    1. Similar to Django's cached_propery: https://github.com/django/django/blob/master/django/utils/functional.py#L34

      Delete