Static caching property

Ethan Furman ethan at stoneleaf.us
Mon Mar 21 13:45:35 EDT 2016


On 03/21/2016 10:03 AM, Joseph L. Casale wrote:
>> 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.
>> I will look at that, I wonder if however I am not over complicating it:
>> class Foo:
> _bar = None
> @property
> def expensive(self):
> if Foo._bar is None:
> import something
> Foo._bar = something.expensive()
> return Foo._bar
>> Somewhat naive, but a test with if is pretty cheap...

A slightly cleaner approach (but only slightly):
 class Cache(object):
 _sentinal = object()
 def __init__(self, expensive_func):
 self.value = self._sentinal
 self.func = expensive_func
 def __get__(self, *args):
 if self.value is self._sentinal:
 self.value = self.func()
 return self.func()
The advantages:
- only one location in the class
- works correctly whether accessed via class or instance
- clue as to functionality in the name
--
~Ethan~


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /