Static caching property
Chris Angelico
rosuav at gmail.com
Mon Mar 21 20:15:49 EDT 2016
On Tue, Mar 22, 2016 at 11:05 AM, Steven D'Aprano <steve at 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
More information about the Python-list
mailing list