Easy caching

jalanb3 yahoo at al-got-rhythm.net
Thu Nov 13 00:24:40 EST 2008


Evening all, 

And thank you for your valuable reading skills.

The following pattern turned up in coding tonight.
It works, but I'm suspicious, it just seems too easy.

So any comments or constructive criticisms welcome ?

*** Start doctest format ***

	>>> 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 as a method, get the value
	>>> print cacher.show
	9

show is now a cached string
	>>> print cacher.show
	9

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

***

-- 
Alan






More information about the Python-list mailing list