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.coreLet 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_countNotice display_name function is decorated with @attribute. The first call promotes function to attribute with the same name. The source is here.
Labels:
algorithms
,
python
,
wheezy.core
Subscribe to:
Post Comments
(
Atom
)
2 comments :
Welcome to @reify
Reply Deletehttps://github.com/Pylons/pyramid/blob/master/pyramid/decorator.py
Similar to Django's cached_propery: https://github.com/django/django/blob/master/django/utils/functional.py#L34
Delete