Static caching property

Ian Kelly ian.g.kelly at gmail.com
Tue Mar 22 09:30:33 EDT 2016


On Mon, Mar 21, 2016 at 6:05 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Tue, 22 Mar 2016 04:48 am, Ian Kelly wrote:
>
>> 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
>
>
> This won't quite work. What if the cached value happens to be falsey, yet
> still expensive to compute? You should compare it to a known sentinel which
> the expensive function will never return (possibly None). Or use a hasattr
> test: if not hasattr(type, '_cached_value').

Sure. This was just a quick-and-dirty demonstration that I threw
together in 30 seconds.

> Also, you don't need the default type=None. The descriptor protocol should
> never call __get__ without supplying the type. The obj may be None, but I
> don't believe there are any circumstances where type will be None.

Why do the examples in the Python docs use type=None? I literally just
copy-pasted the method signature from there, since I can never
remember which argument comes first.



More information about the Python-list mailing list