Decorators not worth the effort
andrea crotti
andrea.crotti.0 at gmail.com
Fri Sep 14 10:12:26 EDT 2012
I think one very nice and simple example of how decorators can be used is this:
def memoize(f, cache={}, *args, **kwargs):
def _memoize(*args, **kwargs):
key = (args, str(kwargs))
if not key in cache:
cache[key] = f(*args, **kwargs)
return cache[key]
return _memoize
def fib(n):
if n <= 1:
return 1
return fib(n-1) + fib(n-2)
@memoize
def fib_memoized(n):
if n <= 1:
return 1
return fib_memoized(n-1) + fib_memoized(n-2)
The second fibonacci looks exactly the same but while the first is
very slow and would generate a stack overflow the second doesn't..
I might use this example for the presentation, before explaining what it is..
More information about the Python-list
mailing list