On Sat, Jun 22, 2013 at 7:10 AM, Steven D'Aprano <st...@pearwood.info> wrote: > The function attribute "__closure__" is set to None for regular functions. > For closures, it is set to a bunch of stuff needed for the inner function to > work correctly. (No user serviceable parts inside.) Basically, the inner > function needs to carry around with it a little piece of its environment, so > it can retrieve the value of "arg" when required.
Using a tuple of cells (loaded from __closure__) allows for fast lookups. If you check with dis, you'll see the ops used with cells are LOAD_DEREF and STORE_DEREF. These handle the indirection through the cell object, which is a flat cost. It's not a function of nesting level. Using cells also avoids referencing the outer frame(s), which would interfere with garbage collection (GC). One catch with Python nested scopes is that binding a name defaults to the local scope. You can get around this by using a mutable container, just as was done with globals before the "global" keyword was added in version 0.9.4 (1991). The better solution is a new keyword, but adding keywords is radical surgery. The "nonlocal" keyword, as Peter used, had to wait for 3.x. _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor