473,410 Members | 1,875 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,410 software developers and data experts.

Easier way to save result of a function?

Sorry for the clunky subject line - I have a feeling that not knowing
the proper terms for this is part of my problem.

I'm trying to write a class that analyses some data. I only want it to
do as much work as necessary, so it saves method results to a
dictionary, like so:
class MyClass:
def __init__(self):
self.data = {}

def doSomething(self):
return self.data.setdefault("someresult", self._doSomething())

def _doSomething(self):
# heavy processing here
result = 1
return result

def doMore(self):
return self.data.setdefault("moreresult", self._doMore())

def _doMore(self):
# more heavy processing here
return self.doSomething() + 1
This also seems kind of clunky. Is there a better way to acheive this?
Or is this the usual idiom for this kind of thing? I've looked at
decorators as they seem like they could be used for this, but I've no
idea how exactly, or even if they're the appropriate tool.

Thanks.

--
James Mitchelhill
ja***@disorderfeed.net
http://disorderfeed.net
Jul 4 '06 #1
5 2423
James Mitchelhill wrote:
Sorry for the clunky subject line - I have a feeling that not knowing
the proper terms for this is part of my problem.

I'm trying to write a class that analyses some data. I only want it to
do as much work as necessary, so it saves method results to a
dictionary, like so:
The term for this is 'memoization'. You can find several recipes for
this in the online Python Cookbook; for example, see
http://aspn.activestate.com/ASPN/Coo.../Recipe/466320

Jul 4 '06 #2
James Mitchelhill <ja***@disorderfeed.netwrote:
Sorry for the clunky subject line - I have a feeling that not knowing
the proper terms for this is part of my problem.

I'm trying to write a class that analyses some data. I only want it to
do as much work as necessary, so it saves method results to a
dictionary, like so:
class MyClass:
def __init__(self):
self.data = {}

def doSomething(self):
return self.data.setdefault("someresult", self._doSomething())

def _doSomething(self):
# heavy processing here
result = 1
return result

def doMore(self):
return self.data.setdefault("moreresult", self._doMore())

def _doMore(self):
# more heavy processing here
return self.doSomething() + 1
This also seems kind of clunky. Is there a better way to acheive this?
Or is this the usual idiom for this kind of thing? I've looked at
decorators as they seem like they could be used for this, but I've no
idea how exactly, or even if they're the appropriate tool.
No, this code is calling the heavy-processing functions
*unconditionally* -- Python's semantics is to compute every argument of
a function or method before starting to execute the code of that
function or method (almost all languages behave that way, save a very
few "pure" functional languages!), and that applies to the setdefault
methods of dictionaries too.

What you want to do is called "memoization" (sometimes "caching", but
that's a very generic term used in a bazillion different situations and
you may get overwhelmed by search results if you try searching for
it!-), and you can find plenty of recipes for it in the Python Cookbook
and elsewhere on the net.

For your needs, I would suggest first defining your class "normally"
(writing the methods without memoization) and then looping on all
methods of interest decorating them with automatic memoization; I just
suggested a similar kind of looping for decoration purposes in my very
latest post on another thread;-). You won't use the _syntax_ of
decorators, but, hey, who cares?-)

Assuming (for simplicity but with no real loss of conceptual generality)
that all of your heavy-processing methods have names starting with 'do',
and that each of them takes only 'self' as its argument, you could for
example do something like:

def memoizeMethod(cls, n, m):
def decorated(self):
if n in self._memo: return self._memo[n]
result = self._memo[n] = m(self)
return result
decorated.__name__ = n
setattr(cls, n, decorated)

def memoizeClass(cls):
cls._memo = {}
for n,m in inspect.getmembers(cls, inspect.ismethoddescriptors):
if not n.startswith('do'): continue
memoizeMethod(cls, n, m)

Now just write your MyClass with the doThis doThat methods you want, and
right after the class statement add

memoizeClass(MyClass)
Voila, that's it (untested details, but the general idea is sound;-).
Alex
Jul 4 '06 #3
On Tue, 4 Jul 2006 16:53:27 -0700, Alex Martelli wrote:
James Mitchelhill <ja***@disorderfeed.netwrote:
<snip>
>I'm trying to write a class that analyses some data. I only want it to
do as much work as necessary, so it saves method results to a
dictionary
<snip>
For your needs, I would suggest first defining your class "normally"
(writing the methods without memoization) and then looping on all
methods of interest decorating them with automatic memoization; I just
suggested a similar kind of looping for decoration purposes in my very
latest post on another thread;-). You won't use the _syntax_ of
decorators, but, hey, who cares?-)

Assuming (for simplicity but with no real loss of conceptual generality)
that all of your heavy-processing methods have names starting with 'do',
and that each of them takes only 'self' as its argument, you could for
example do something like:
Thanks, that's awesome! Definitely not something I'd have ever been able
to work out myself - I think I need to learn more about nested functions
and introspection.
def memoizeMethod(cls, n, m):
def decorated(self):
if n in self._memo: return self._memo[n]
result = self._memo[n] = m(self)
return result
decorated.__name__ = n
setattr(cls, n, decorated)

def memoizeClass(cls):
cls._memo = {}
for n,m in inspect.getmembers(cls, inspect.ismethod):
if not n.startswith('do'): continue
memoizeMethod(cls, n, m)
(I've changed inspect.ismethoddescriptors to inspect.ismethod and
unindented the last line.)
Now just write your MyClass with the doThis doThat methods you want, and
right after the class statement add

memoizeClass(MyClass)
Voila, that's it (untested details, but the general idea is sound;-).
Thanks again.

--
James Mitchelhill
ja***@disorderfeed.net
http://disorderfeed.net
Jul 5 '06 #4
Ant
Thanks, that's awesome! Definitely not something I'd have ever been able
to work out myself - I think I need to learn more about nested functions
and introspection.
I've recently found nested functions incredibly useful in many places
in my code, particularly as a way of producing functions that are
pre-set with some initialization data. I've written a bit about it
here: http://antroy.blogspot.com/ (the entry about Partial Functions)
def memoizeMethod(cls, n, m):
def decorated(self):
if n in self._memo: return self._memo[n]
result = self._memo[n] = m(self)
return result
decorated.__name__ = n
setattr(cls, n, decorated)
Couldn't this be more simply written as:

def memoizeMethod(cls, n, m):
def decorated(self):
if not n in self._memo:
self._memo[n] = m(self)
return self._memo[n]
decorated.__name__ = n
setattr(cls, n, decorated)

I've not seen the use of chained = statements before. Presumably it
sets all variables to the value of the last one?

Jul 5 '06 #5
Ant <an****@gmail.comwrote:
Thanks, that's awesome! Definitely not something I'd have ever been able
to work out myself - I think I need to learn more about nested functions
and introspection.

I've recently found nested functions incredibly useful in many places
in my code, particularly as a way of producing functions that are
pre-set with some initialization data. I've written a bit about it
here: http://antroy.blogspot.com/ (the entry about Partial Functions)
def memoizeMethod(cls, n, m):
def decorated(self):
if n in self._memo: return self._memo[n]
result = self._memo[n] = m(self)
return result
decorated.__name__ = n
setattr(cls, n, decorated)

Couldn't this be more simply written as:

def memoizeMethod(cls, n, m):
def decorated(self):
if not n in self._memo:
self._memo[n] = m(self)
return self._memo[n]
decorated.__name__ = n
setattr(cls, n, decorated)
Yes, at a tiny performance cost (probably hard to measure), though I
would spell the guard "if n not in self._memo:" :-).

I've not seen the use of chained = statements before. Presumably it
sets all variables to the value of the last one?
It sets all ``variables'' ("left-hand sides", LHS) to the right-hand
side (RHS) value; here, it lets you avoid an extra indexing in order to
obtain the value to return (a tiny cost, to be sure).
Alex
Jul 5 '06 #6

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

Similar topics

4
by: dan glenn | last post by:
(PHP4.3.4, GD2) How can I save a PNG using GD2 and insure that it saves as a palette-based (8-bit, 256-color) single-color transparancy?? Saving this way, I could be sure that an image loaded from...
73
by: RobertMaas | last post by:
After many years of using LISP, I'm taking a class in Java and finding the two roughly comparable in some ways and very different in other ways. Each has a decent size library of useful utilities...
1
by: Kenneth McDonald | last post by:
I'm working on the 0.8 release of my 'rex' module, and would appreciate feedback, suggestions, and criticism as I work towards finalizing the API and feature sets. rex is a module intended to make...
3
by: Felix Kater | last post by:
Hi, normally I use a local variable assigned to different return values inside the function and return it like this: int f(){ int my_err_code; my_err_code=1;
10
by: GJP | last post by:
Hello. Ive been asked to make my own notepade for college assignment. All ig going well, but i cant get the save to work. I can get Save a (shows dialog box), i can get it to just save too,...
10
by: Niyazi | last post by:
Hi, I developed an application and I am using SQL Server 2000 developer edition. I create my database and I have also created tbl_USER table. I have an ID, RealName, UserName, and UserPassword...
1
by: Michael | last post by:
Hi Everyone, I have a simple page right now to save an PO info to the server. I get the following error: "ExecuteNonQuery requires the command to have a transaction when the connection assigned...
3
by: mo | last post by:
I have an application that uses Reporting Services. When the user chooses to print a report, they are taken to a window that allows them to fill in parameters for the report. They then click a...
1
by: cleary1981 | last post by:
Hi, I have this script for backing up a database that when it is run the option comes up to save the file. Can anyone show me how I would change this script so that the script automatically saves...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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,...
0
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...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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...

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.