<[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
| I'm wondering, are there some general cases where __call__ methods of
| a user-defined class are simply indispensable?
One classical example (untested, based on memory of posted code):
class memoize():
def __init__(self, func):
self.func = func
self.memo = {}
def __call__(self, *args):
try:
return self.memo[args]
except KeyError:
res = self.func(*args)
self.memo[args] = res
return res
Before Py2.2 closures, I might have called this indispensible. Since no
attributes are rebound, this can now be written
def memoize(func):
memo = {}
def _(*args)
try:
return memo[args]
except KeyError:
res = func(*args)
memo[args] = res
return res
return _
This is a bit simpler, but one gives up both direct external access to the
memo dict and any other methods, such as a customized
def __repr__(self):
return "memoize wrapper for %s" % self.func
or possibly a method to empty (or partially empty) the memo dict.
If I were writing about memoization for programmers in general, just using
Python, I would give both forms since many languages (including Py2.1-) do
not have both forms, even if they have one.
Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list