Thursday, November 13, 2008

Easy cache

No bailouts required.

And if you don't believe it,
    you can copy and paste this to a doctest file:


>>> class Cacher:
... def __init__(self):
... self.value_in_database = 0
...
... def very_slow_database_access(self):
... return self.value_in_database
...
... @property
... def show(self):
... result = self.very_slow_database_access()
... self.show = result
... return result
...
>>>

Create an instance
>>> cacher = Cacher()

Someone writes to the database

>>> cacher.value_in_database = 9

Call show for the first time,
which will get the value from the database

>>> print cacher.show
9

show is now cached

show is not a method so
if someone else writes to the database
we will not see the change

>>> cacher.value_in_database = 7
>>> print cacher.show
9

To force another read from the database
delete the string attribute

>>> del cacher.show

Next time we try to use the attribute
Python will find the method again

>>> print cacher.show
7

Labels: , , , , , , ,

0 Comments:

Post a Comment

<< Home