Re: [SQLObject] caching an expensive property
SQLObject is a Python ORM.
Brought to you by:
ianbicking,
phd
|
From: Oleg B. <ph...@ph...> - 2014-12-10 00:20:10
|
On Wed, Dec 10, 2014 at 01:09:50AM +0100, "Fetchinson ." <fet...@go...> wrote:
> On 12/10/14, Oleg Broytman <ph...@ph...> wrote:
> > you'd better implement your own
> > caching with proper locking.
>
> Well, that was exactly the question, how would I do that? :)
> Precisely for the reason you mention above I was wary of using a more
> or less standard caching decorator. Can't I attach the computed value
> to the instance itself somehow by setting a new property?
The classical approach is:
def __init__(self):
self.__cache = None
self.__cache_lock = Lock()
def _get_value(self):
if self.__cache is not None:
return self.__cache
self.__cache_lock.acquire()
try:
if self.__cache is not None: # Calculated in another thread
return self.__cache
self.__cache = ...do expensive calculation once...
return self.__cache
finally: # finally works both for exceptions and returns
self.__cache_lock.release()
Oleg.
--
Oleg Broytman http://phdru.name/ ph...@ph...
Programmers don't die, they just GOSUB without RETURN.
|