There is a tutorial at http://pythonprogramming.jottit.com/functional_programming and it gives an example how to use higher order functions to return functions:
def trace(f):
f.indent = 0
def g(x):
print '| ' * f.indent + '|--', f.__name__, x
f.indent += 1
value = f(x)
print '| ' * f.indent + '|--', 'return', repr(value)
f.indent -= 1
return value
return g
and
def memoize(f):
cache = {}
def g(x):
if x not in cache:
cache[x] = f(x)
return cache[x]
return g
but I don’t get how it’s able to assign two functions on the same variable on the statements:
fib = trace(fib)
fib = memoize(fib)
print fib(4)
both trace and memoize seem to have effect on the last call. Why is that?
Both
trace()andmemoize()create a new function object and return it to you.In each case, the new function object “wraps” the old function object, so the original function is not lost.
Using my amazing ASCII art skills, here is a diagram:
We start out with a function object bound to the name
fib.Then we call
trace(fib)which creates a new function object. When it is first created, its name isgbut we then bind it to the namefib. Try printingfib.__name__.Then we call
memoize(fib)which creates a new function object. Again it’s first created with the name ofgbut then bound to the namefib.Remember, in Python everything is an object, and objects can exist with no name, with one name, or with many names. In this case, we keep re-using the name
fibbut we keep re-binding it with different function objects.