473,589 Members | 2,570 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to memoize/cache property access?

I seem to be writing the following boilerplate/pattern quite
frequently to avoid hitting the database until absolutely necessary,
and to only do it at most once:

class Foo(object):
@property
def expensive(self) :
if not hasattr(self, '_expensiv'):
self._expensive = <insert expensive db call here>
return self._expensive

it's a bit verbose, and it violates the DRY (Don't Repeat Yourself)
principle -- and it has on at least one occasion resulted in really
slow code that produces the correct results (did you spot the typo
above?).

It would have been nice to be able to write

class Foo(object):
@property
def expensive(self) :
self.expensive = <insert expensive db call here>
return self.expensive

but apparently I "can't set [that] attribute" :-(

I'm contemplating using a decorator to hide the first pattern:

def memprop(fn):
def _fn(self): # properties only take self
memname = '_' + fn.__name__
if not hasattr(self, memname):
setattr(self, memname, fn(self))
return getattr(self, memname)
return property(fget=_ fn, doc=fn.__doc__)

which means I can very simply write

class Foo(object):
@memprop
def expensive(self) :
return <insert expensive db call here>

I'm a bit hesitant to start planting home-grown memprop-s all over the
code-base though, so I'm wondering... does this seem like a reasonable
thing to do? Am I re-inventing the wheel? Is there a better way to
approach this problem?

-- bjorn
Dec 20 '07 #1
4 3025
thebjorn <Bj************ ************@gm ail.comwrote:
It would have been nice to be able to write

class Foo(object):
@property
def expensive(self) :
self.expensive = <insert expensive db call here>
return self.expensive

but apparently I "can't set [that] attribute" :-(
You can set and access it directly in __dict__. How about something along
these lines:

def cachedproperty( f):
name = f.__name__
def getter(self):
try:
return self.__dict__[name]
except KeyError:
res = self.__dict__[name] = f(self)
return res
return property(getter )

class Foo(object):
@cachedproperty
def expensive(self) :
print "expensive called"
return 42
>>f = Foo()
f.expensive
expensive called
42
>>f.expensive
42

It is still calling the getter every time though, so not as fast as a plain
attribute lookup.
Dec 20 '07 #2
On Dec 20, 5:02 pm, thebjorn <BjornSteinarFj eldPetter...@gm ail.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:

$ cat cache.py
class cached(property ):
'Convert a method into a cached attribute'
def __init__(self, method):
private = '_' + method.__name__
def fget(s):
try:
return getattr(s, private)
except AttributeError:
value = method(s)
setattr(s, private, value)
return value
def fdel(s):
del s.__dict__[private]
super(cached, self).__init__( fget, fdel=fdel)
@staticmethod
def reset(self):
cls = self.__class__
for name in dir(cls):
attr = getattr(cls, name)
if isinstance(attr , cached):
delattr(self, name)

if __name__ == '__main__': # a simple test
import itertools
counter = itertools.count ()
class Test(object):
@cached
def foo(self):
return counter.next()
reset = cached.reset

p = Test()
print p.foo
print p.foo
p.reset()
print p.foo
print p.foo
p.reset()
print p.foo

Michele Simionato
Dec 20 '07 #3
On Dec 20, 5:43 pm, Michele Simionato <michele.simion ...@gmail.com>
wrote:
On Dec 20, 5:02 pm, thebjorn <BjornSteinarFj eldPetter...@gm ail.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(sel f):
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

Dec 20 '07 #4
On Dec 20, 6:40 pm, thebjorn
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?
My use case is for web applications where the configuration
parameters are stored in a database. If you change them,
you can re-read them by resetting the configuration object
(you may have a reset button in the administrator Web user
interface) without restarting the application.

Michele Simionato

Dec 20 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
4206
by: Chris Reedy | last post by:
I would like to memoize (I think I've got that right) a collection of functions for a project I'm working. <Aside for those not familiar with memoizing functions:> Given: def foo(a,b,c): return <result of large ugly computation>
3
4008
by: Michael Hohn | last post by:
Hi, under python 2.2, the pickle/unpickle sequence incorrectly restores a larger data structure I have. Under Python 2.3, these structures now give an explicit exception from Pickle.memoize(): assert id(obj) not in self.memo I'm shrinking the offending data structure down to find the problem
13
2347
by: km | last post by:
Hi all, was going thru the new features introduced into python2.4 version. i was stuck with 'decorators' - can someone explain me the need of such a thing called decorators ? tia KM
3
489
by: George Ter-Saakov | last post by:
What is HttpContext.Cache for ? The usual HttpRequest lasts miliseconds. Why would someone to cache anything? We do have HttpContext.Items to keep any extra info during the request. Can someone explain me the use of the HttpContext.Cache. Thanks.
2
1631
by: Keith Chadwick | last post by:
Need some help on access the httpApplication cache. I was informed to use the application cache over the old application object and also to use a classes versus modules. do I need to Imprt System.Web.HttpApplication into the class? do I need to dim x as System.Web.Application then use x.context.cache.item("myitem")=myobject
1
1413
by: Christopher | last post by:
In one of our ASP.NET Pages, we are starting a new background thread that we do not need to go and get any status on or use after the page finishes. The thread merely does some background stuff on its own and finishes on its own, no feedback back to the user (by design). Within that thread however, some items need to be accessed and/or inserted into the Cache for possible subsequent processing by another page. Many examples I see of...
11
2508
by: thattommyhallll | last post by:
im plugging away at the problems at http://www.mathschallenge.net/index.php?section=project im trying to use them as a motivator to get into advanced topics in python. one thing that Structure And Interpretation Of Computer Programs teaches is that memoisation is good. all of the memoize decorators at the python cookbook seem to make my code slower. is using a decorator a lazy and inefficient way of doing memoization? can anyone point...
4
15115
by: Harry Haller | last post by:
What's wrong with this: Error 3 'System.Web.Caching.Cache' is a 'type', which is not valid in the given context public List<AssetSummaryGetAssetSummary() { return (List<AssetSummary>)System.Web.Caching.Cache("assetSummary"); }
1
2878
by: Andrus | last post by:
I need to create Dlinq entity property value caches for every entity and every property so that all entity caches can cleared if entity of this type is changed. Entity class method uses this as: string GetCustomerNameById( string customerId ) { var cache = CacheManager.Get<Customer,string, string>("CustomerName"); string res; if (cache.TryGetValue(customerId , out res)) return res;
0
7931
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7865
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8233
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8360
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7990
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6637
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5731
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5399
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
1198
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.