Skip to content

Instantly share code, notes, and snippets.

@samartioli
Last active December 16, 2015 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samartioli/5452095 to your computer and use it in GitHub Desktop.
Save samartioli/5452095 to your computer and use it in GitHub Desktop.
From the example at: http://ujihisa.blogspot.com/2010/11/memoized-recursive-fibonacci-in-python.html How do I access the cache of fibonacci numbers after running the function?
def memoize(f):
cache = {}
def decorated_function(*args):
if args in cache:
return cache[args]
else:
cache[args] = f(*args)
return cache[args]
return decorated_function
@memoize
def fib(n):
return n if n < 2 else fib(n-2) + fib(n-1)
SOLUTION: Assign the local variable to an attribute after the function definition before returning it.
def memoize(f):
cache = {}
def decorated_function(*args):
if args in cache:
return cache[args]
else:
cache[args] = f(*args)
return cache[args]
decorated_function.cache = cache
return decorated_function
@memoize
def fib(n):
return n if n < 2 else fib(n-2) + fib(n-1)
print fib(10)
print fib.cache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment