Why do closures do this?

John O'Hagan research at johnohagan.com
Sat Aug 27 23:45:05 EDT 2011


Somewhat apropos of the recent "function principle" thread, I was recently surprised by this:

funcs=[]
for n in range(3):
    def f():
        return n
    funcs.append(f)

[i() for i in funcs]

The last expression, IMO surprisingly, is [2,2,2], not [0,1,2]. Google tells me I'm not the only one surprised, but explains that it's because "n" in the function "f" refers to whatever "n" is currently bound to, not what it was bound to at definition time (if I've got that right), and that there are at least two ways around it: either make a factory function:

def mkfnc(n):
    def fnc():
        return n
    return fnc

funcs=[]
for n in range(3):
    funcs.append(mkfnc(n))

which seems roundabout, or take advantage of the "default values set at definition time" behaviour:

funcs=[]
for n in range(3):
    def f(n=n):
        return n
    funcs.append(f)

which seems obscure, and a side-effect.

My question is, is this an inescapable consequence of using closures, or is it by design, and if so, what are some examples of where this would be the preferred behaviour?

Regards,

John 



More information about the Python-list mailing list