@decorator syntax is sugar, but for what exactly? (decorator libraries).

xtian xtian at toysinabag.com
Tue Aug 10 19:39:47 EDT 2004


Skip Montanaro <skip at pobox.com> wrote in message news:<mailman.1467.1092158118.5135.python-list at python.org>...
>
>     class martha:
>         memo = {}
> 
>         @staticmethod
>         def memoize(func):
>             if func not in martha.memo:
>                 martha.memo[func] = {}
>             def _inner(*args, **kwds):
>                 items = kwds.items()
>                 items.sort()
>                 items = tuple(items)
>                 key = (args, items)
>                 try:
>                     val = martha.memo[key]
>                 except KeyError:
>                     val = func(*args, **kwds)
>                     martha.memo[key] = val
>                 return val
>             return _inner
> 
>     @martha.memoize
>     def fib(n):
>         assert n >= 0
>         print n
>         if n <= 1:
>             return 1
>         return n + fib(n-1)
> 
>     print fib(5)
>     print fib(4)
> 
> Running that yields this output:
> 
>     5
>     4
>     3
>     2
>     1
>     15
>     10
> 
> Skip


Minor typo - I think the references to martha.memo[key] in _inner
should be to martha.memo[func][key], enabling you to prevent different
memoized functions' results from clashing when they were called with
the same parameters.

You can check this by adding another memoized function:

@martha.memoize
def fact(n):
    assert n >= 0
    print n
    if n <= 1:
        return 1
    return n * fact(n-1)

print "fact(5) = %d" % fact(5)

If you add that to the end of the file, it'll give the wrong answer
without the change.

Sorry Skip - obviously you know this, which is why you've got the
martha.memo[func] = {} line there. I just thought it was worth
pointing out in case someone put it into their toolkit and then got
bit much later on when they memoized a second function that was called
with the same arguments.

It's a nice example of a useful decorator though - the syntax is
definitely growing on me, especially in a syntax-highlighted editor
where the def is more prominent because of colouring.

Thanks,
xtian



More information about the Python-list mailing list