Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #105482
| From | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Static caching property |
| Date | 2016-03-22 07:30 -0600 |
| Message-ID | <mailman.11.1458653480.2244.python-list@python.org> (permalink) |
| References | (2 earlier) <56f0230e$0$1616$c3e8da3$5496439d@news.astraweb.com> <e043630368254fdeab16f0967df6662f@activenetwerx.com> <CAPTjJmqvu4qMpcbR-g5QZG6neuJVcHrKLYLDFe5QC_QBQbd2-g@mail.gmail.com> <mailman.453.1458582555.12893.python-list@python.org> <56f08c59$0$1590$c3e8da3$5496439d@news.astraweb.com> |
On Mon, Mar 21, 2016 at 6:05 PM, Steven D'Aprano <steve@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.
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Re: Static caching property Ian Kelly <ian.g.kelly@gmail.com> - 2016-03-21 10:15 -0600
Re: Static caching property Steven D'Aprano <steve@pearwood.info> - 2016-03-22 03:36 +1100
Re: Static caching property "Joseph L. Casale" <jcasale@activenetwerx.com> - 2016-03-21 16:49 +0000
Re: Static caching property Chris Angelico <rosuav@gmail.com> - 2016-03-22 03:54 +1100
Re: Static caching property "Joseph L. Casale" <jcasale@activenetwerx.com> - 2016-03-21 17:03 +0000
Re: Static caching property Ian Kelly <ian.g.kelly@gmail.com> - 2016-03-21 11:44 -0600
Re: Static caching property Ethan Furman <ethan@stoneleaf.us> - 2016-03-21 10:45 -0700
Re: Static caching property Ian Kelly <ian.g.kelly@gmail.com> - 2016-03-21 11:48 -0600
Re: Static caching property Steven D'Aprano <steve@pearwood.info> - 2016-03-22 11:05 +1100
Re: Static caching property Chris Angelico <rosuav@gmail.com> - 2016-03-22 11:15 +1100
Re: Static caching property Ian Kelly <ian.g.kelly@gmail.com> - 2016-03-22 07:30 -0600
csiph-web