Lazy Attribute

Ian Kelly ian.g.kelly at gmail.com
Thu Nov 15 23:24:40 CET 2012


On Thu, Nov 15, 2012 at 12:33 PM, Andriy Kornatskyy
<andriy.kornatskyy at live.com> wrote:
>
> A lazy attribute is an attribute that is calculated on demand and only once.
>
> The post below shows how you can use lazy attribute in your Python class:
>
> http://mindref.blogspot.com/2012/11/python-lazy-attribute.html
>
> Comments or suggestions are welcome.

The name "attribute" is not very descriptive.  Why not "lazy_attribute" instead?

I note that trying to access the descriptor on the class object
results in an error:

>>> from descriptors import attribute
>>> class Foo:
...     @attribute
...     def forty_two(self):
...         return 6 * 9
...
>>> Foo().forty_two
54
>>> Foo.forty_two
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".\descriptors.py", line 33, in __get__
    setattr(obj, f.__name__, val)
AttributeError: 'NoneType' object has no attribute 'forty_two'

If accessing the descriptor on the class object has no special
meaning, then the custom is to return the descriptor object itself, as
properties do.

>>> class Foo:
...     @property
...     def forty_two(self):
...         return 6 * 9
...
>>> Foo().forty_two
54
>>> Foo.forty_two
<property object at 0x0280AD80>


More information about the Python-list mailing list