Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #33402

Re: Lazy Attribute

References <DUB117-W881D7D74D529D159D8B33F91520@phx.gbl>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2012-11-15 15:24 -0700
Subject Re: Lazy Attribute
Newsgroups comp.lang.python
Message-ID <mailman.3728.1353018314.27098.python-list@python.org> (permalink)

Show all headers | View raw


On Thu, Nov 15, 2012 at 12:33 PM, Andriy Kornatskyy
<andriy.kornatskyy@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>

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Lazy Attribute Ian Kelly <ian.g.kelly@gmail.com> - 2012-11-15 15:24 -0700

csiph-web