I am looking at some learning material here: http://anandology.com/python-practice-book/functional-programming.html#higher-order-functions-decorators
Particularly the Memoize
section, in which the following code is used as an example for higher-order functions:
def memoize(f):
cache = {}
def g(x):
if x not in cache:
cache[x] = f(x)
return cache[x]
return g
It was my understanding that the function returned by memoize would not have access to the "cache" variable since it is out of scope of the definition of "g".
Eg. if I do result_function = memoize(some_function)
that result_function
would have no knowledge of any cache
variable since it is declared outside the g
function and the g
function alone is returned. Why does it work, and not throw an error?