On Mon, Mar 21, 2016 at 6:05 PM, Steven D'Aprano <st...@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. -- https://mail.python.org/mailman/listinfo/python-list