In article <5257c3dd$0$29984$c3e8da3$54964...@news.astraweb.com>, Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote:
> On Fri, 11 Oct 2013 10:14:29 +0300, Jussi Piitulainen wrote: > > > Roy Smith writes: > >> In article <m2a9ihxf3a....@cochabamba.vanoostrum.org>, > >> Piet van Oostrum wrote: > >> > >> > I usually say that a closure is a package, containing a function with > >> > some additional data it needs. The data usually is in the form of > >> > name bindings. > >> > >> That's pretty close to the way I think about it. The way it was > >> originally described to me is, "A closure is a function bundled up with > >> it's arguments". > > > > Really? It should be more like "a function bundled up with some other > > function's arguments" and even more like "a function bundled up with > > bindings for its free variables". > > Closures have nothing to do with *arguments*. A better definition of a > closure is that it is a function together with a snapshot of the > environment it was called from. > > def func(arg): > y = arg + 1 > def inner(): > return y + 1000 > return inner > > f = func(1) Maybe a better example of closure would be (just for the nonlocal) : def fib() : (a,b) = (0,1) def producer() : nonlocal a,b # Python 3 old = a (a,b) = (b,a+b) return old return producer >>> f = fib() >>> [f() for i in range(10)] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] > At this point, f is a closure. It needs to know the value of y (not the > argument to func) in order to work, and the implementation is to store > that information inside f.func_closure (or f.__closure__ in Python 3). > The part of the calling environment which is saved is y Shouldn't it be the (a,b) pair here ? But : >>> f.__closure__[0].cell_contents # access to what ? 55 Shouldn't cell_contents keep the current (a,b) pair, a part of the snapshot of the creation environment (private variables of the closure) ? Instead it seems to returns only a (which is the next production)... franck -- https://mail.python.org/mailman/listinfo/python-list