How to memoize/cache property access?
thebjorn
BjornSteinarFjeldPettersen at gmail.com
Thu Dec 20 12:40:28 EST 2007
On Dec 20, 5:43 pm, Michele Simionato <michele.simion... at gmail.com>
wrote:
> On Dec 20, 5:02 pm, thebjorn <BjornSteinarFjeldPetter... at gmail.com>
> wrote:
>
> > I seem to be writing the following boilerplate/pattern quite
> > frequently to avoid hitting the database until absolutely necessary ...
>
> I use the following module:
[...]
I love it! much better name too ;-)
I changed your testcase to include a second cached property (the
naming is in honor of my late professor in Optimization of Functional
Languages class: "...any implementation that calls bomb_moscow is per
definition wrong, even if the program produces the correct result..."
-- it was a while ago ;-)
if __name__ == '__main__': # a simple test
import itertools
counter = itertools.count()
class Test(object):
@cached
def foo(self):
return counter.next()
@cached
def bomb_moscow(self):
print 'fire missiles'
return counter.next()
reset = cached.reset
it didn't start WWIII, but I had to protect attribute deletion to get
it to run:
def fdel(s):
if private in s.__dict__:
del s.__dict__[private]
I'm a bit ambivalent about the reset functionality. While it's a
wonderful demonstration of a staticmethod, the very few times I've
felt the need to "freshen-up" the object, I've always felt it was best
to create it again from scratch. Do you have many uses of it in your
code?
-- bjorn
More information about the Python-list
mailing list