On Tue, 4 Jul 2006 16:53:27 -0700, Alex Martelli wrote: > James Mitchelhill <[EMAIL PROTECTED]> wrote: <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 [EMAIL PROTECTED] http://disorderfeed.net -- http://mail.python.org/mailman/listinfo/python-list