On Mon, Mar 21, 2016 at 10:54 AM, Chris Angelico <ros...@gmail.com> wrote: > On Tue, Mar 22, 2016 at 3:49 AM, Joseph L. Casale > <jcas...@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 -- https://mail.python.org/mailman/listinfo/python-list