Static caching property

Ian Kelly ian.g.kelly at gmail.com
Mon Mar 21 13:48:27 EDT 2016


On Mon, Mar 21, 2016 at 10:54 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Tue, Mar 22, 2016 at 3:49 AM, Joseph L. Casale
> <jcasale at activenetwerx.com> wrote:
>> Right, but _private refers to an api call that is expensive and may not even be accessed,
>> so while I may new up three instances of Test across a, b and c, if none of those end up
>> accessing var x, it shouldn't get fetched. Without some deferred execution, if the value
>> of _private is a callable whose return value is what I am interested in, it gets invoked the
>> moment the class is compiled.
>>
>> In the non static sense this is trivial to accomplish with the descriptor protocol, I am just not
>> clear for the static sense.
>
> One solution is to use descriptor protocol on the class, which means
> using a metaclass. I'm not sure it's the best option, but it is an
> option.

You don't actually need a metaclass for this:

>>> class Desc:
...     def __get__(self, obj, type=None):
...         if not type._cached_value:
...             type._cached_value = compute_value(type)
...         return type._cached_value
...
>>> def compute_value(x): return 42
...
>>> class Test:
...     foo = Desc()
...     _cached_value = None
...
>>> Test._cached_value
>>> Test.foo
42
>>> Test._cached_value
42



More information about the Python-list mailing list