How to automate accessor definition?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Tue Mar 23 05:13:05 EDT 2010


John Posner a écrit :
> On 3/22/2010 11:44 AM, Bruno Desthuilliers wrote:
> 
> <snip>
> 
>> Another (better IMHO) solution is to use a plain property, and store the
>> computed value as an implementation attribute :
>>
>> @property
>> def foo(self):
>> cached = self.__dict__.get('_foo_cache')
>> if cached is None:
>> self._foo_cache = cached = self._some_time_consuming_operation()
>> return cached
>>
> 
> There's no need to access __dict__ directly.

Nope, inded. I guess I wrote it that way to make clear that we were 
looking for an instance attribute (as a sequel of my previous writing on 
attribute lookup rules).

> I believe this is 
> equivalent (and clearer):
> 
>  @property
>  def foo(self):
>      try:
>          cached = self._foo_cache
>      except AttributeError:
>          self._foo_cache = cached = self._time_consuming_op()
>      return cached
> 

This is functionally _almost_ equivalent - won't work the same if 
there's a class attribute "_foo_cache", which might or not be a good 
thing !-)

Will possibly be a bit faster after the first access - IIRC setting up 
an error handler is by itself cheaper than doing a couple attribute 
access and a method call - but I'd timeit before worrying about it.



More information about the Python-list mailing list