__call__ considered harmful or indispensable?

Terry Reedy tjreedy at udel.edu
Thu Aug 2 17:12:27 EDT 2007


<skip at pobox.com> wrote in message 
news:18098.8872.263489.36952 at montanaro.dyndns.org...
| 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






More information about the Python-list mailing list