Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #105419

Re: Static caching property

From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Subject Re: Static caching property
Date 2016-03-22 11:15 +1100
Message-ID <mailman.474.1458605752.12893.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>

Show all headers | View raw


On Tue, Mar 22, 2016 at 11:05 AM, Steven D'Aprano <steve@pearwood.info> wrote:
> But my favourite is to combine them:
>
>
> class Desc:
>     def __get__(self, obj, type):
>         sentinel = object()  # guaranteed to be unique
>         value = getattr(type, _cached_value, sentinel)
>         if value is sentinel:
>             value = type._cached_value = compute_value(type)
>         return value
>
>
>

That seems like overkill. Inside getattr is the equivalent of:

try: return type._cached_value
except AttributeError: return sentinel

So skip getattr/hasattr and just use try/except:

class Desc:
    def __get__(self, obj, type):
        try:
            return type._cached_value
        except AttributeError:
            value = type._cached_value = compute_value(type)
            return value

ChrisA

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


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