I guess this is more like a Python question, but I guess it would be
very useful for speeding up some computations in sage. I took the
definition for the Memoize class from the net, but does not quite work
as I want for methods.
Consider the following:
class Memoize:
"""Memoize(fn) - an instance which acts like fn but memoizes its
arguments
Will only work on functions with non-mutable arguments; since it
uses
the arguments as keys for a dictionary, and hence the keys need
to be
hashable.
"""
def __init__(self, fn):
self.fn = fn
self.memo = {}
def __call__(self, *args):
if args not in self.memo:
self.memo[args] = self.fn(*args)
return self.memo[args]
class dog():
def __init__(self,bark='guau'):
self.bark=bark
@Memoize
def bark(self):
sleep (5)
return bark+' '+bark+' '+bark
sparky=dog()
The only way to run the above example is sparky.bark(sparky) or
dog.bark(sparky), since sparky.bark() does not work. Removing the
decorator, sparky.bark() works but takes 5 seconds everytime, unlike
the Memoized version.
Is there a way to have a version of Memoize that behaves nicely with
methods? A redirection to the appropriate page or documentation is
also ok.
Thanks.
Peace.
-Adrian.
--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/sage-support
URLs: http://www.sagemath.org
-~----------~----~----~----~------~----~------~--~---