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 ***
... def __init__(self):
... self.value_in_d atabase = 0
...
... def very_slow_datab ase_access(self ):
... return self.value_in_d atabase
...
... @property
... def show(self):
... result = self.very_slow_ database_access ()
... self.show = result
... return result
...
Create an instance
Someone writes to the database
Call show as a method, get the value
9
show is now a cached string
9
show is not a method so
if someone else writes to the database
we will not see the change
9
To force another read from the database
delete the string attribute
Next time we try to use the attribute
Python will find the method again
7
***
--
Alan
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:
... self.value_in_d atabase = 0
...
... def very_slow_datab ase_access(self ):
... return self.value_in_d atabase
...
... @property
... def show(self):
... result = self.very_slow_ database_access ()
... self.show = result
... return result
...
>>>
>>cacher = Cacher()
>>cacher.value_ in_database = 9
>>print cacher.show
show is now a cached string
>>print cacher.show
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
>>print cacher.show
To force another read from the database
delete the string attribute
>>del cacher.show
Python will find the method again
>>print cacher.show
***
--
Alan
Comment