Easier way to save result of a function?

James Mitchelhill james at disorderfeed.net
Tue Jul 4 19:38:51 EDT 2006


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
james at disorderfeed.net
http://disorderfeed.net



More information about the Python-list mailing list