Function decorator that caches function results

Tom Anderson twic at urchin.earth.li
Thu Oct 13 02:49:52 CEST 2005


On Tue, 10 Oct 2005, it was written:

> Tom Anderson <twic at urchin.earth.li> 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,

You're right. I don't think it's wrong, but it depends on the reader 
knowing what i mean by 'variable'. I didn't make it clear that variables 
live in an *invocation* of a function, not a definition. IOW, in this 
code:

def foo():
 	x = 1
foo()
foo()

There are two occurrances of assignment, and they are to two *different* 
variables.

Hmm. Maybe i *am* wrong - looking at your example:

>  For example:
>  def f(n):
>     def g(): return n
>     return g
>  h1 = f(1)
>  h2 = f(2)

h1 and h2 are closures, while g is "a function in which some of the 
variable names refer to variables outside the function", but is not a 
closure.

So a closure is something that is created when a function is taken out of 
its lexical environment (through being returned, or passed downwards, or 
stored on the heap); when you take it out, it retains a connection to that 
environment. What we need now is a good metaphor for this ...

> 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).

I was trying to avoid the word 'lexical', since a lot of people aren't too 
clear on what that means.

> 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.

That's quite a good way of explaining it. The thing about closures is that 
they're really obvious when you actually write them, but rather tricky to 
define in words. So, perhaps the best explanation is to walk the reader 
through an example.

> This is all described in SICP (mitpress.mit.edu/sicp).

A lot of things are described in SICP. ISTM that someone should not have 
to read the whole of SICP to understand what closures are.

tom

-- 
That's no moon!



More information about the Python-list mailing list