Skip to content

Instantly share code, notes, and snippets.

@reillyeon
Last active December 21, 2015 18:48
Show Gist options
  • Save reillyeon/6349482 to your computer and use it in GitHub Desktop.
Save reillyeon/6349482 to your computer and use it in GitHub Desktop.
import functools
def compute_once(f):
class ComputeOnce(object):
def __call__(self):
value = f()
self.__class__.__call__ = lambda x: value
return value
return ComputeOnce()
def memoize(f):
d = {}
@functools.wraps(f)
def compute(*args, **kwargs):
key = (args, tuple(kwargs.items()))
try:
return d[key]
except KeyError:
value = f(*args, **kwargs)
d[key] = value
return value
return compute
@memoize
def fib(n, a=1):
print "fib(%d)" % n
if n < 3:
return 1
else:
return fib(n-1) + fib(n-2)
@compute_once
def return_one():
print "Executing"
return 1
@compute_once
def return_two():
print "Executing"
return 2
print fib
print fib(10, a=2)
print return_one
print return_one()
print return_one()
print return_two()
print return_two()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment