Memoizing decorator

Alex Martelli aleax at mail.comcast.net
Tue Dec 6 00:54:32 EST 2005


Scott David Daniels <scott.daniels at acm.org> wrote:

> Daishi Harada wrote:
> > ...  I've managed to get these working for both
> > functions and methods by wrapping them in
> > yet another function (the following is for the
> > cookbook example, replacing 'cachedmethod'):
> > 
> > ---
> > def memoize(function):
> >     im = Memoize(function)
> >     def fn(*args, **kwargs):
> >         return im(*args, **kwargs)
> >     return fn
> > ---
> But, this is equivalent to:
>    def memoize(function):
>        im = Memoize(function)
>        return im

It's only equivalent if Memoize returns a function, or another
descriptor whose __get__ behaves like a function's.  In other words, if
Memoize is a class with a __call__ method, you need to add to it a
__get__ method able to bind the `self' argument (and if you want
complete emulation of Memoize being a function, its __get__ method must
also be able to produce the type-checking equivalent of the unbound
method objects that a function's __get__ would build).

Only when such a __get__ method is in class Memoize does this
simplification work, and similarly for the further ones you show:

> Which is (in turn) equivalent to:
>    memoize = Memoize
> 
> So you can just use
>      @Memoize
>      def function (....


Alex



More information about the Python-list mailing list