Function decorator that caches function results

Paul Rubin http
Tue Oct 11 02:04:47 CEST 2005

Tom Anderson <twic at> writes:
> Okay, a crack at a definition: a closure is a function in which some
> of the variable names refer to variables outside the function.

That's misleading, I'd say a closure is a combination of a function
(executable code) and a lexical environment (the values of the
function's free variables, as taken from surrounding scopes at the
time the function was created).  For example:
  def f(n):
     def g(): return n
     return g
  h1 = f(1)
  h2 = f(2)

h1 and h2 are two different closures.  They have the same executable
code but their environments are different.  In h1, n=1, but in h2, n=2.
So, h1() will return 1 but h2() will return 2.  Is there really anything
confusing about this?  All that's happened is that when you call f, f
allocates a memory slot for n.  g makes a reference to the slot and
then f returns.  Since the reference to the slot still exists, the slot
doesn't get GC'd.  When you call f again, it allocates a new slot.

This is all described in SICP (  

More information about the Python-list mailing list